引入与创建overlay
import Overlay from "ol/Overlay";// 创建map实例以及其他地图操作请看前几篇文章
// 省略2k行代码methods: {creatMark(markDom, txt, idstr) {if (markDom == null) {markDom = document.createElement("div");if (txt) {markDom.innerHTML = `<div>经度:${txt[0]}</div><div>纬度:${txt[1]}</div>`;} else {markDom.innerHTML = txt;}markDom.style ="width:auto;height:auto;padding:4px;border:1px solid #409EFF;font-size:12px;background-color:#fff;position:relative;top:60%;left:60%;font-weight:600;";}let overlay = new Overlay({element: markDom,autoPan: false,positioning: "bottom-center",id: idstr,stopEvent: false,});this.map.addOverlay(overlay);return overlay;},
}
这里,我传入了3个变量:
- markDom:标记的dom元素
- txt:标记中要显示的信息,比如 传入的是经纬度数据 [127.00000, 31.00000]
- idstr:为的是标记overlay,唯一标识
调用与清除overlay
this.map.on("click", (evt) => {// 获取当前点击点的 feature,如果存在就移除const feature = this.pointLayerSource.getFeatureById("curIconFeatureId");// 清除元素if (feature) {this.pointLayerSource.removeFeature(feature);}// 清除overlayconst overlay= this.map.getOverlayById("featureInfo");if (overlay) {this.map.removeOverlay(overlay);}this.addFeature(evt, this.markerCurrentIcon, "curIconFeatureId", true);});
如果你高兴,this.cerateMark随意传值来优化标记样式效果,也可以将overlay的id存入data中。