把接口返回的经纬度集合点,在高德地图上标记展示,这个需求估计大家都不陌生
但是存在一个问题,那就是加载地图消耗的带宽过多,所以就需要优化方案
当然,首先想到的,就是,地图只初始化加载一次,局部更新标记点就好了!
根据这个需求方案,我们开始开发
<template>
<section>
<section class="map_warpper">
<div id="container" class="map"></div>
</section>
</section>
</template>
<script>
import util from ‘@/libs/util.js‘
import { QueryLocation } from ‘@/api/dashboard‘
import redMarker from ‘@/assets/img/marker-red.png‘
import locationMarker from ‘@/assets/img/marker-location.png‘
export default {
name: ‘dashboard-mapContainer‘,
props: [‘moduleId‘],
data () {
return {
locationArray: [],
markers: [],
cluster: [],
setInterval: ‘‘,
map: null,
regionLocation: [],
zoom: 0
}
},
watch: {
moduleId: function (val, oldVal) {
// 清除点
this.cluster.Ra = []
// 进行缩放,局部刷新视图
this.map.setZoom(this.zoom - 2)
this.queryLocation()
}
},
created () {
this.queryLocation()
},
mounted () {
this.initMap()
},
methods: {
queryLocation () {
this.locationArray = []
QueryLocation({
moduleId: parseInt(this.moduleId),
regionId: parseInt(util.cookies.get(‘regionId‘)),
startPos: 0,
maxCount: 99
}).then(res => {
const data = res.data
for (const index in data.list) {
this.locationArray[index] = data.list[index].location
}
if (data.list.length > 0) {
this.setMarker()
} else {
// 没数据时初始化
this.map.setZoom(12)
this.map.setCenter(this.regionLocation)
}
}).catch(err => {
console.log(err)
// 请求失败时初始化
this.map.setZoom(12)
this.map.setCenter(this.regionLocation)
})
},
// 实例化地图
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
})
},
// 设置点标记
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, bug总是不经意间出现,比如,明明每次执行setMarker()时都会 this.markers = [],
按道理说,标记点应该是要更新的,而且并删除掉以前的旧点,然后发现事实并非如此,旧点和新点都同时出现,
而且随着叠加,越来越多,这问题就来了,这时记得queryLocation()调用前强行删除点 this.cluster.Ra = [],
然后发现点集合虽然每次都更新了,但视图依旧是老问题,这当然也难不倒我们,发现只要缩放一下地图就正常了,
可能是高德地图加载视图没更新,还需要触发才行,这好办
通过 this.map.getZoom()获取当前缩放级别,然后通过 this.map.setZoom()设置缩放,就刷新了视图,好了,问题解决
原文:https://www.cnblogs.com/wx3091/p/12082768.html