index.vue 18.8 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
<template>
2 3
  <uni-map
    :id="id"
Q
qiang 已提交
4
    v-on="$listeners"
fxy060608's avatar
fxy060608 已提交
5
  >
Q
qiang 已提交
6 7 8 9 10
    <map-marker
      v-for="item in markers"
      :key="item.id"
      v-bind="item"
    />
11 12 13 14 15
    <map-polygon
      v-for="item in polygons"
      :key="JSON.stringify(item)"
      v-bind="item"
    />
d-u-a's avatar
d-u-a 已提交
16 17
    <div
      ref="map"
Q
qiang 已提交
18
      style="width: 100%; height: 100%; position: relative; overflow: hidden"
fxy060608's avatar
fxy060608 已提交
19
    />
Q
qiang 已提交
20 21 22 23 24 25 26 27 28 29
    <div
      style="
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        pointer-events: none;
      "
    >
X
xiaoyucoding 已提交
30
      <slot />
郭胜强 已提交
31 32
    </div>
  </uni-map>
fxy060608's avatar
fxy060608 已提交
33 34 35 36 37 38
</template>

<script>
import {
  subscriber
} from 'uni-mixins'
39

X
xiaoyucoding 已提交
40
import {
Q
qiang 已提交
41 42 43 44
  loadMaps
} from './maps'

import mapMarker from './map-marker'
45
import mapPolygon from './map-polygon/index'
X
xiaoyucoding 已提交
46

Q
qiang 已提交
47 48
import { ICON_PATH_ORIGIN } from '../../../helpers/location'

Q
qiang 已提交
49 50 51
function getLat (latLng) {
  if ('getLat' in latLng) {
    return latLng.getLat()
52
  } else {
Q
qiang 已提交
53 54 55 56 57 58 59 60 61
    return latLng.lat()
  }
}

function getLng (latLng) {
  if ('getLng' in latLng) {
    return latLng.getLng()
  } else {
    return latLng.lng()
62 63 64
  }
}

fxy060608's avatar
fxy060608 已提交
65 66
export default {
  name: 'Map',
Q
qiang 已提交
67
  components: {
68 69
    mapMarker,
    mapPolygon
Q
qiang 已提交
70
  },
fxy060608's avatar
fxy060608 已提交
71 72 73 74 75 76
  mixins: [subscriber],
  props: {
    id: {
      type: String,
      default: ''
    },
77
    latitude: {
fxy060608's avatar
fxy060608 已提交
78
      type: [String, Number],
79
      default: 39.92
fxy060608's avatar
fxy060608 已提交
80
    },
81
    longitude: {
fxy060608's avatar
fxy060608 已提交
82
      type: [String, Number],
83
      default: 116.46
fxy060608's avatar
fxy060608 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    },
    scale: {
      type: [String, Number],
      default: 16
    },
    markers: {
      type: Array,
      default () {
        return []
      }
    },
    covers: {
      type: Array,
      default () {
        return []
      }
    },
101
    includePoints: {
fxy060608's avatar
fxy060608 已提交
102 103 104 105 106
      type: Array,
      default () {
        return []
      }
    },
107
    polyline: {
fxy060608's avatar
fxy060608 已提交
108 109 110 111 112
      type: Array,
      default () {
        return []
      }
    },
113
    circles: {
fxy060608's avatar
fxy060608 已提交
114 115 116 117 118
      type: Array,
      default () {
        return []
      }
    },
119
    controls: {
fxy060608's avatar
fxy060608 已提交
120 121 122 123 124 125 126 127
      type: Array,
      default () {
        return []
      }
    },
    showLocation: {
      type: [Boolean, String],
      default: false
Q
qiang 已提交
128 129 130 131 132 133
    },
    libraries: {
      type: Array,
      default () {
        return []
      }
134 135 136 137
    },
    polygons: {
      type: Array,
      default: () => []
fxy060608's avatar
fxy060608 已提交
138 139 140 141 142
    }
  },
  data () {
    return {
      center: {
143 144
        latitude: 116.46,
        longitude: 116.46
fxy060608's avatar
fxy060608 已提交
145 146 147 148 149
      },
      isMapReady: false,
      isBoundsReady: false,
      polylineSync: [],
      circlesSync: [],
150
      controlsSync: []
fxy060608's avatar
fxy060608 已提交
151 152 153
    }
  },
  watch: {
154 155
    latitude () {
      this.centerChange()
fxy060608's avatar
fxy060608 已提交
156
    },
157 158
    longitude () {
      this.centerChange()
fxy060608's avatar
fxy060608 已提交
159 160 161
    },
    scale (val) {
      this.mapReady(() => {
162
        this._map.setZoom(Number(val) || 16)
fxy060608's avatar
fxy060608 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
      })
    },
    polyline (val) {
      this.mapReady(() => {
        this.createPolyline()
      })
    },
    circles () {
      this.mapReady(() => {
        this.createCircles()
      })
    },
    controls () {
      this.mapReady(() => {
        this.createControls()
      })
    },
    includePoints () {
      this.mapReady(() => {
        this.fitBounds(this.includePoints)
      })
    },
    showLocation (val) {
      this.mapReady(() => {
        this[val ? 'createLocation' : 'removeLocation']()
      })
    }
  },
  created () {
Q
qiang 已提交
192
    this._markers = {}
fxy060608's avatar
fxy060608 已提交
193 194 195 196 197 198 199 200
    var latitude = this.latitude
    var longitude = this.longitude
    if (latitude && longitude) {
      this.center.latitude = latitude
      this.center.longitude = longitude
    }
  },
  mounted () {
Q
qiang 已提交
201 202
    loadMaps(this.libraries, result => {
      this._maps = result
fxy060608's avatar
fxy060608 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216
      this.init()
    })
  },
  beforeDestroy () {
    this.removePolyline()
    this.removeCircles()
    this.removeControls()
    this.removeLocation()
  },
  methods: {
    _handleSubscribe ({
      type,
      data = {}
    }) {
Q
qiang 已提交
217
      const maps = this._maps
fxy060608's avatar
fxy060608 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
      function callback (res, err) {
        res = res || {}
        res.errMsg = `${type}:${err ? 'fail' + err : 'ok'}`
        var cb = err ? data.fail : data.success
        if (typeof cb === 'function') {
          cb(res)
        }
        if (typeof data.complete === 'function') {
          data.complete(res)
        }
      }

      switch (type) {
        case 'getCenterLocation':
          this.mapReady(() => {
            var latitude
            var longitude
235
            var center = this._map.getCenter()
Q
qiang 已提交
236 237
            latitude = getLat(center)
            longitude = getLng(center)
fxy060608's avatar
fxy060608 已提交
238 239 240 241 242 243 244

            callback({
              latitude: latitude,
              longitude: longitude
            })
          })
          break
Q
qiang 已提交
245 246 247 248 249 250 251 252
        case 'moveToLocation':
          {
            const { latitude, longitude } = data
            var locationPosition = (latitude && longitude) ? new maps.LatLng(latitude, longitude) : this._locationPosition
            if (locationPosition) {
              this._map.setCenter(locationPosition)
              callback({})
            }
fxy060608's avatar
fxy060608 已提交
253 254 255 256 257 258 259 260 261 262
          }
          break
        case 'translateMarker':
          this.mapReady(() => {
            try {
              var marker = this.getMarker(data.markerId)
              var destination = data.destination
              var duration = data.duration
              var autoRotate = !!data.autoRotate
              var rotate = Number(data.rotate) ? data.rotate : 0
Q
qiang 已提交
263 264 265 266
              let rotation = 0
              if ('getRotation' in marker) {
                rotation = marker.getRotation()
              }
fxy060608's avatar
fxy060608 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
              var a = marker.getPosition()
              var b = new maps.LatLng(destination.latitude, destination.longitude)
              var distance = maps.geometry.spherical.computeDistanceBetween(a, b) / 1000
              var time = ((typeof duration === 'number') ? duration : 1000) / (1000 * 60 * 60)
              var speed = distance / time
              var movingEvent = maps.event.addListener(marker, 'moving', e => {
                var latLng = e.latLng
                var label = marker.label
                if (label) {
                  label.setPosition(latLng)
                }
                var callout = marker.callout
                if (callout) {
                  callout.setPosition(latLng)
                }
              })
              var event = maps.event.addListener(marker, 'moveend', e => {
                event.remove()
                movingEvent.remove()
                marker.lastPosition = a
                marker.setPosition(b)
                var label = marker.label
                if (label) {
                  label.setPosition(b)
                }
                var callout = marker.callout
                if (callout) {
                  callout.setPosition(b)
                }
                var cb = data.animationEnd
                if (typeof cb === 'function') {
                  cb()
                }
              })
              var lastRtate = 0
              if (autoRotate) {
                if (marker.lastPosition) {
                  lastRtate = maps.geometry.spherical.computeHeading(marker.lastPosition, a)
                }
                rotate = maps.geometry.spherical.computeHeading(a, b) - lastRtate
              }
Q
qiang 已提交
308 309 310 311 312 313 314 315 316
              if ('setRotation' in marker) {
                marker.setRotation(rotation + rotate)
              }
              if ('moveTo' in marker) {
                marker.moveTo(b, speed)
              } else {
                marker.setPosition(b)
                maps.event.trigger(marker, 'moveend', {})
              }
fxy060608's avatar
fxy060608 已提交
317 318 319 320 321 322 323 324 325 326
            } catch (error) {
              callback(null, error)
            }
          })
          break
        case 'includePoints':
          this.fitBounds(data.points)
          break
        case 'getRegion':
          this.boundsReady(() => {
327
            var latLngBounds = this._map.getBounds()
fxy060608's avatar
fxy060608 已提交
328 329 330 331
            var southwest = latLngBounds.getSouthWest()
            var northeast = latLngBounds.getNorthEast()
            callback({
              southwest: {
Q
qiang 已提交
332 333
                latitude: getLat(southwest),
                longitude: getLng(southwest)
fxy060608's avatar
fxy060608 已提交
334 335
              },
              northeast: {
Q
qiang 已提交
336 337
                latitude: getLat(northeast),
                longitude: getLng(northeast)
fxy060608's avatar
fxy060608 已提交
338 339 340 341 342 343 344
              }
            })
          })
          break
        case 'getScale':
          this.mapReady(() => {
            callback({
345
              scale: this._map.getZoom()
fxy060608's avatar
fxy060608 已提交
346 347 348 349 350 351
            })
          })
          break
      }
    },
    init () {
Q
qiang 已提交
352
      const maps = this._maps
fxy060608's avatar
fxy060608 已提交
353
      var center = new maps.LatLng(this.center.latitude, this.center.longitude)
354
      var map = this._map = new maps.Map(this.$refs.map, {
fxy060608's avatar
fxy060608 已提交
355 356
        center,
        zoom: Number(this.scale),
357
        // scrollwheel: false,
fxy060608's avatar
fxy060608 已提交
358 359 360 361
        disableDoubleClickZoom: true,
        mapTypeControl: false,
        zoomControl: false,
        scaleControl: false,
362
        panControl: false,
Q
qiang 已提交
363 364 365
        fullscreenControl: false,
        streetViewControl: false,
        keyboardShortcuts: false,
fxy060608's avatar
fxy060608 已提交
366 367 368 369 370 371 372 373 374 375
        minZoom: 5,
        maxZoom: 18,
        draggable: true
      })
      var boundsChangedEvent = maps.event.addListener(map, 'bounds_changed', e => {
        boundsChangedEvent.remove()
        this.isBoundsReady = true
        this.$emit('boundsready')
      })
      maps.event.addListener(map, 'click', () => {
d-u-a's avatar
d-u-a 已提交
376 377
        // TODO 编译器将 tap 转换为click
        this.$trigger('click', {}, {})
fxy060608's avatar
fxy060608 已提交
378 379 380
      })
      maps.event.addListener(map, 'dragstart', () => {
        this.$trigger('regionchange', {}, {
381 382
          type: 'begin',
          causedBy: 'gesture'
fxy060608's avatar
fxy060608 已提交
383 384
        })
      })
385 386 387 388 389
      function getMapInfo () {
        var center = map.getCenter()
        return {
          scale: map.getZoom(),
          centerLocation: {
Q
qiang 已提交
390 391
            latitude: getLat(center),
            longitude: getLng(center)
392 393 394
          }
        }
      }
fxy060608's avatar
fxy060608 已提交
395
      maps.event.addListener(map, 'dragend', () => {
396 397 398 399
        this.$trigger('regionchange', {}, Object.assign({
          type: 'end',
          causedBy: 'drag'
        }, getMapInfo()))
fxy060608's avatar
fxy060608 已提交
400 401 402
      })
      maps.event.addListener(map, 'zoom_changed', () => {
        this.$emit('update:scale', map.getZoom())
403 404 405 406
        this.$trigger('regionchange', {}, Object.assign({
          type: 'end',
          causedBy: 'scale'
        }, getMapInfo()))
fxy060608's avatar
fxy060608 已提交
407 408 409 410 411
      })
      maps.event.addListener(map, 'center_changed', () => {
        var latitude
        var longitude
        var center = map.getCenter()
Q
qiang 已提交
412 413
        latitude = getLat(center)
        longitude = getLng(center)
fxy060608's avatar
fxy060608 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        this.$emit('update:latitude', latitude)
        this.$emit('update:longitude', longitude)
      })
      if (this.polyline && Array.isArray(this.polyline) && this.polyline.length) {
        this.createPolyline()
      }
      if (this.circles && Array.isArray(this.circles) && this.circles.length) {
        this.createCircles()
      }
      if (this.controls && Array.isArray(this.controls) && this.controls.length) {
        this.createControls()
      }
      if (this.showLocation) {
        this.createLocation()
      }
      if (this.includePoints && Array.isArray(this.includePoints) && this.includePoints.length) {
        this.fitBounds(this.includePoints, () => {
          map.setCenter(center)
        })
      }
      this.isMapReady = true
      this.$emit('mapready')
Q
qiang 已提交
436
      this.$trigger('updated', {}, {})
fxy060608's avatar
fxy060608 已提交
437
    },
438
    centerChange () {
Q
qiang 已提交
439
      const maps = this._maps
440 441 442 443 444 445 446 447 448 449 450 451
      var latitude = Number(this.latitude)
      var longitude = Number(this.longitude)
      if (latitude !== this.center.latitude || longitude !== this.center.longitude) {
        this.center.latitude = latitude
        this.center.longitude = longitude
        if (this._map) {
          this.mapReady(() => {
            this._map.setCenter(new maps.LatLng(latitude, longitude))
          })
        }
      }
    },
fxy060608's avatar
fxy060608 已提交
452
    createPolyline () {
Q
qiang 已提交
453
      const maps = this._maps
454
      var map = this._map
fxy060608's avatar
fxy060608 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
      var polyline = this.polylineSync
      this.removePolyline()
      this.polyline.forEach(option => {
        var path = []
        option.points.forEach(point => {
          path.push(new maps.LatLng(point.latitude, point.longitude))
        })

        if (option.borderWidth) {
          var border = new maps.Polyline({
            map,
            clickable: false,
            path,
            strokeWeight: option.width + option.borderWidth,
            strokeColor: option.borderColor,
            strokeDashStyle: option.dottedLine ? 'dash' : 'solid'
          })
          polyline.push(border)
        }
        var line = new maps.Polyline({
          map,
          clickable: false,
          path,
          strokeWeight: option.width,
          strokeColor: option.color,
          strokeDashStyle: option.dottedLine ? 'dash' : 'solid'
        })
        polyline.push(line)
      })
    },
    removePolyline () {
      var polyline = this.polylineSync
      polyline.forEach(line => {
        line.setMap(null)
      })
      polyline.splice(0, polyline.length)
    },
    createCircles () {
Q
qiang 已提交
493
      const maps = this._maps
494
      var map = this._map
fxy060608's avatar
fxy060608 已提交
495 496 497 498 499 500
      var circles = this.circlesSync
      this.removeCircles()
      this.circles.forEach(option => {
        var center = new maps.LatLng(option.latitude, option.longitude)

        function getColor (color) {
Q
qiang 已提交
501 502 503 504 505 506 507
          var c = color && color.match(/#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?/)
          if ('Color' in maps) {
            if (c && c.length) {
              return maps.Color.fromHex(c[0], Number('0x' + c[1] || 255) / 255)
            } else {
              return undefined
            }
fxy060608's avatar
fxy060608 已提交
508
          }
Q
qiang 已提交
509
          return color
fxy060608's avatar
fxy060608 已提交
510 511 512 513 514 515
        }
        var circle = new maps.Circle({
          map,
          center,
          clickable: false,
          radius: option.radius,
Q
qiang 已提交
516 517 518
          strokeWeight: Number(option.strokeWidth) || 1,
          fillColor: getColor(option.fillColor) || getColor('#00000001'),
          strokeColor: getColor(option.color) || '#000000',
fxy060608's avatar
fxy060608 已提交
519 520 521 522 523 524 525 526 527 528 529 530 531
          strokeDashStyle: 'solid'
        })
        circles.push(circle)
      })
    },
    removeCircles () {
      var circles = this.circlesSync
      circles.forEach(circle => {
        circle.setMap(null)
      })
      circles.splice(0, circles.length)
    },
    createControls () {
Q
qiang 已提交
532
      const maps = this._maps
533
      var _self = this
534
      var map = this._map
fxy060608's avatar
fxy060608 已提交
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
      var controls = this.controlsSync
      this.removeControls()
      this.controls.forEach(option => {
        var position = option.position || {}
        var control = document.createElement('div')
        var img = new Image()
        control.appendChild(img)
        var style = control.style
        style.position = 'absolute'
        style.width = 0
        style.height = 0
        img.onload = () => {
          if (option.position.width) {
            img.width = option.position.width
          }
          if (option.position.height) {
            img.height = option.position.height
          }
          var style = img.style
          style.position = 'absolute'
          style.left = (position.left || 0) + 'px'
          style.top = (position.top || 0) + 'px'
          style.maxWidth = 'initial'
        }
559
        img.src = this.$getRealPath(option.iconPath)
560
        img.onclick = function ($event) {
fxy060608's avatar
fxy060608 已提交
561
          if (option.clickable) {
562
            _self.$trigger('controltap', $event, {
fxy060608's avatar
fxy060608 已提交
563 564 565
              controlId: option.id
            })
          }
566
        }
fxy060608's avatar
fxy060608 已提交
567 568 569 570 571 572 573 574 575 576 577 578
        map.controls[maps.ControlPosition.TOP_LEFT].push(control)
        controls.push(control)
      })
    },
    removeControls () {
      var controls = this.controlsSync
      controls.forEach(control => {
        control.remove()
      })
      controls.splice(0, controls.length)
    },
    createLocation () {
Q
qiang 已提交
579
      const maps = this._maps
580 581
      var map = this._map
      var location = this._location
fxy060608's avatar
fxy060608 已提交
582 583 584 585 586 587
      if (location) {
        this.removeLocation()
      }
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
588
          if (location !== this._location) {
fxy060608's avatar
fxy060608 已提交
589 590 591 592 593 594
            return
          }
          var position = new maps.LatLng(res.latitude, res.longitude)
          location = new maps.Marker({
            position,
            map,
Q
qiang 已提交
595
            icon: new maps.MarkerImage(ICON_PATH_ORIGIN, null, null, new maps.Point(22, 22), new maps.Size(44, 44)),
fxy060608's avatar
fxy060608 已提交
596 597 598
            flat: true,
            rotation: 0
          })
599
          this._location = location
fxy060608's avatar
fxy060608 已提交
600
          refreshLocation()
Q
qiang 已提交
601
          this.__onCompassChange = function (res) {
fxy060608's avatar
fxy060608 已提交
602
            location.setRotation(res.direction)
Q
qiang 已提交
603 604
          }
          uni.onCompassChange(this.__onCompassChange)
fxy060608's avatar
fxy060608 已提交
605 606 607 608 609 610 611 612
        },
        fail: e => {
          console.error(e)
        }
      })
      var self = this

      function refreshLocation () {
613
        if (location !== self._location) {
fxy060608's avatar
fxy060608 已提交
614 615 616 617 618 619
          return
        }
        setTimeout(() => {
          uni.getLocation({
            type: 'gcj02',
            success: (res) => {
620
              var locationPosition = self._locationPosition = new maps.LatLng(res.latitude, res.longitude)
fxy060608's avatar
fxy060608 已提交
621 622 623 624 625 626 627 628 629
              location.setPosition(locationPosition)
            },
            fail: e => {
              console.error(e)
            },
            complete: () => {
              refreshLocation()
            }
          })
Q
qiang 已提交
630
        }, 30000)
fxy060608's avatar
fxy060608 已提交
631 632 633
      }
    },
    removeLocation () {
634
      var location = this._location
fxy060608's avatar
fxy060608 已提交
635 636
      if (location) {
        location.setMap(null)
637 638
        this._location = null
        this._locationPosition = null
Q
qiang 已提交
639
        uni.offCompassChange(this.__onCompassChange)
fxy060608's avatar
fxy060608 已提交
640 641 642
      }
    },
    fitBounds (points, cb) {
Q
qiang 已提交
643
      const maps = this._maps
fxy060608's avatar
fxy060608 已提交
644
      this.boundsReady(() => {
645
        var map = this._map
fxy060608's avatar
fxy060608 已提交
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        var bounds = new maps.LatLngBounds()

        points.forEach(point => {
          var longitude = point.longitude
          var latitude = point.latitude
          var latLng = new maps.LatLng(latitude, longitude)
          bounds.extend(latLng)
        })
        map.fitBounds(bounds)
        if (typeof cb === 'function') {
          cb()
        }
      })
    },
    mapReady (cb) {
      if (this.isMapReady) {
        cb()
      } else {
        this.$once('mapready', () => {
          cb()
        })
      }
    },
    boundsReady (cb) {
      if (this.isBoundsReady) {
        cb()
      } else {
        this.$once('boundsready', () => {
          cb()
        })
      }
    },
    getMarker (id) {
Q
qiang 已提交
679 680 681
      var marker = this._markers[id]
      if (!marker) {
        throw new Error('translateMarker: fail cannot find marker with id ' + id)
fxy060608's avatar
fxy060608 已提交
682
      }
Q
qiang 已提交
683
      return marker
fxy060608's avatar
fxy060608 已提交
684 685 686 687 688 689
    }
  }
}
</script>

<style>
X
xiaoyucoding 已提交
690 691 692 693 694 695 696 697 698 699
	uni-map {
		position: relative;
		width: 300px;
		height: 150px;
		display: block;
	}

	uni-map[hidden] {
		display: none;
	}
d-u-a's avatar
d-u-a 已提交
700
</style>