將接口返回的經緯集合點在高德地圖上標記展示, 如果實時刷新地圖標記點,不加優化,則會造成過多的帶寬消耗 所以,地圖只需加載一次,局部更新標記點就好了
代碼:
<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()設置縮放,視圖達到刷新,問題解決