谨以此记录vue项目中,在高德地图基础上绘制分区的业务场景:
高德地图初始化:
// 初始化地图
initMap() {
let $AMap = window.AMap
if($AMap) {
this.map = new $AMap.Map("map", {
zoom: mapConfig.defaultZoom, // 地图缩放比例
expandZoomRange: true,
zooms: [8, 20],
center: mapConfig.defaultCenter, // 地图中心店
pitch: 0,
viewMode: "2D",
mapStyle: "amap://styles/e3408e73e03eeaba546fb05d0b7ea46a"
});
this.getData(data); // 获取分区范围数据 data 为后端请求回来的数据
}
},
getData(data) {
// 清除所有覆盖物
if(this.allPolygon&&this.allPolygon.length) {
this.map.remove(this.allPolygon)
this.allPolygon = []
}
// 清除选中的覆盖物
if(this.activePolygon) {
this.map.remove(this.activePolygon)
this.activePolygon = null
}
this.activeData = null
let $AMap = window.AMap
// this.map.setZoomAndCenter([8, 20], mapConfig.defaultCenter)
if(data.list && data.list.length > 0) {
data.list.forEach(item => {
if(item.GeoJsonData) {
try {
let GeoJsonData = JSON.parse(item.GeoJsonData)
let polygon = new $AMap.Polygon({
bubble: true,
path: GeoJsonData.path, // 坐标集合
fillColor: GeoJsonData.fillColor, // 多边形填充颜色
strokeColor: GeoJsonData.fillColor, // 线条颜色
strokeWeight: 0, // 多边形填充透明度,取值范围[0,1],
strokeStyle: 'solid', // 实线:solid,虚线:dashed
strokeOpacity: 0.5,
fillOpacity: 0.5
});
polygon.setExtData(item);
if(!this.actveParams.find(a => a==item.Level)) {
polygon.hide()
}
this.allPolygon.push(polygon)
this.map.add(polygon);
} catch (error) {
console.log('error', error)
}
}
})
}
// return
if(this.markerModal) {
this.map.remove(this.markerModal)
this.markerModal = null
}
this.markerModal = new $AMap.Marker({
content: '',
position: [0, 0], // 基点位置
zIndex: 9999999,
// offset: new $AMap.Pixel(-200, -122)
});
this.markerModal.hide()
let t = null
this.map.add(this.markerModal)
this.allPolygon.forEach(item => {
let markerData = item.getExtData()
item.on('mouseover', () => {
if(t) clearTimeout(t)
t = setTimeout(() => { // 防止频繁误触
this.markerModal.setPosition([markerData.Lng, markerData.Lat])
this.markerModal.setContent(`<div class="mapModal">
<div class="mapModalImg"></div>
<div class="modalTitle">${markerData.Name || '--'}</div>
<div class="modalContent">
<div class="modalItem">
<span class="modalKey">标题:</span>
<span class="modalValue">标题内容</span>
</div>
<div class="modalItem">
<span class="modalKey">时间:</span>
<span class="modalValue">北京时间</span>
</div>
</div>
</div>`)
this.$nextTick(() => { // 阻止弹窗冒泡
let dom = document.getElementsByClassName('mapModal')[0]
if(dom) {
dom.onmousemove = (e) => {
e.stopPropagation()
return false
}
}
})
this.markerModal.show()
}, 300)
})
item.on('mouseout', () => {
if(t) {
clearTimeout(t)
t = null
}
this.markerModal.hide()
})
})
},