结构,地图+提示弹窗
<div id="homeMap">
<!--提示弹框-->
<div id="popBoxId" v-html="tipContent"></div>
</div>
初始化地图时,定义高亮图层以及弹出框
/**
* 初始化地图
*/
initMap() {
//初始化地图操作,此处省略。。。
...
// 提示框
this.popup = new Overlay({
element: document.getElementById('popBoxId')
})
this.map.addOverlay(this.popup)
this.map.on('pointermove', this.showTipBox)
//高亮显示图层
this.highlightSource = new VectorSource()
let highlightLayer = new VectorLayer({
name: '高亮图层',
source: this.highlightSource,
style: new Style({
stroke: new Stroke({
color: '#c0c0c0',
width: 5
}),
fill: new Fill({
color: 'rgba(255,255,0,1)'
})
}),
zIndex: 100
})
this.map.addLayer(highlightLayer)
}
展示高亮图层以及弹出框
/**
* 展示高亮图层及弹出框
*/
showTipBox(event) {
let pixel = this.map.getEventPixel(event.originalEvent)
let feature = this.map.forEachFeatureAtPixel(pixel, function (feature) {
return feature
})
// 在图层外面的时候,feature和highlight都是null,不执行
// 如果有feature/没有hightlight,就添加feature到图层,并且给highlight赋值。
// 如果feature发生改变,就移除highlight并添加新的feature到图层,然后给highlight改变值。
if (feature !== this.highlightFeature) {
//清空高亮图层样式
if (this.highlightFeature) {
this.highlightSource.removeFeature(this.highlightFeature)
}
//添加新的高亮图层,显示弹窗
if (feature) {
this.highlightSource.addFeature(feature)
let coordinate = event.coordinate
let patchId = feature.getId()
if (patchId !== undefined) {
this.tipContent = '<p>斑块: ' + patchId + '</p>'
this.popup.setPosition(coordinate)
} else {
this.popup.setPosition(undefined)
}
} else {
this.popup.setPosition(undefined)
}
this.highlightFeature = feature
}
}