将接口返回的经纬集合点在高德地图上标记展示, 如果实时刷新地图标记点,不加优化,则会造成过多的带宽消耗 所以,地图只需加载一次,局部更新标记点就好了
代码:
<template>
  <section class="map_warpper">
     <div id="container" class="map"></div>
  </section>
</template>
<script>
import redMarker from '@/assets/img/marker-red.png'
import locationMarker from '@/assets/img/marker-location.png'
export default {
  name: 'mapContainer',
  data () {
    return {
    // 动态的经纬度点集合
      locationArray: [],
      markers: [],
      cluster: [],
      map: null,
      // 地图中心点
      regionLocation: [],
      zoom: 0
    }
  },
  mounted () {
    this.initMap()
  },
  methods: {// 实例化地图
    initMap () {
      this.regionLocation = util.cookies.get('regionLocation').split(',')
      const AMap = window.AMap
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        center: this.regionLocation,
        zoom: 12
      })
     this.setMarker()
    },
    // 设置点标记
    setMarker () {
      this.markers = []
      const AMap = window.AMap
      // 标记样式
      for (const i in this.locationArray) {
        const position = this.locationArray[i].split(',')
        this.markers.push(new AMap.Marker({
          position: position,
          content: '<img src=' + locationMarker + '>',
          offset: new AMap.Pixel(-15, -15)
        }))
      }
      // 聚合点样式
      let sts = [{
        url: redMarker,
        size: new AMap.Size(64, 64),
        offset: new AMap.Pixel(-32, -32)
      }]
      // 点聚合
      this.cluster = new AMap.MarkerClusterer(this.map, this.markers, { styles: sts, gridSize: 80 })
      // 自适应展示所有标记点
      this.map.setFitView(this.markers)
      this.zoom = this.map.getZoom()
    }
  }
}
</script>
<style>
.map {
  width: 100%;
  height: 100%;
}
.map_warpper {
  width: 100%;
  height: 800px;
}
</style> 
上面代码解决了两个bug:
1.每次执行setMarker()时,都会this.markers = [], 这一步清除标记点,驱动地图标记刷新,然而并未刷新,新旧点并存,随着叠加,点会越来越多, 这时记得queryLocation()调用前强行删除点 this.cluster.Ra = []
2.然而集合点更新了,但视图依旧未触发更新,这时就需要缩放地图来触发更新, this.map.getZoom()获取当前缩放级别,然后通过 this.map.setZoom()设置缩放,视图达到刷新,问题解决
