jsapi有提供popup功能,但缺點很多,例如地圖上只能同時顯示一個popup,popup內容有限制等
本文提供另一個方法,原理不用jsapi,在地圖外用一個普通的div放在地圖上面,再監聽地圖的鼠標移動等時間控制這div跟着地圖聯動
本文代碼可能存在跟框架的css等綁定,不一定能直接運行,在此只提供實現思路
本文代碼用到vue的綁定
初始化,寫入popup的數據也在此
popupInit: function () {
//popup初始化
//填入popup的數據
this.popupInfos = [];
this.popupInfos.push({
//地圖座標
x: 113.566806,
y: 22.22445,
//popup內容的文字,只是個示範,當然格式不限
text: "我是第一個",
//是否顯示,不是必須的
show: true,
//樣式
style: {
//div的位置,單位是屏幕座標
top: "-1000px",
left: "-1000px",
},
});
this.popupInfos.push({
x: 113.57418,
y: 22.2234205,
text: "我是第2222個",
show: true,
style: {
top: "-1000px",
left: "-1000px",
},
});
this.popupInfos.push({
x: 113.5928,
y: 22.226853,
text: "我不顯示的",
show: false,
style: {
top: "-1000px",
left: "-1000px",
},
});
},
移動popup位置的方法
//移動popup位置
relocatePopup: function () {
for (let i = 0; i < this.popupInfos.length; i++) {
let popupInfo = this.popupInfos[i];
//把popup所在的地圖座標轉爲屏幕座標
let point = mapUtil.geometry.xyToPoint(this.apiInstance, popupInfo.x, popupInfo.y, this.mapView.spatialReference);
let screenPoint = this.mapView.toScreen(point);
let x = screenPoint.x;
let y = screenPoint.y;
//重新設置popup的div的位置
popupInfo.style.top = y - 114 + 'px';
popupInfo.style.left = x - 100 + 'px';
}
},
監聽地圖事件以實現popup和地圖位置聯動,這段代碼通常在map加載完成時執行
//地圖彈窗移動的實現
//由於popup只是一個在jsapi外部的一般的div,因此這div的移動要自行編碼實現
//原理是監聽地圖所有的會改變地圖顯示範圍的事件(也就是popup需要移動的事件),然後根據地圖座標轉換爲屏幕座標,最終重新設置div的位置
//地圖拖動事件
this.mapView.on('drag', function (e) {
this.relocatePopup();
}.bind(this));
//滾輪事件
this.mapView.on('mouse-wheel', function (e) {
this.relocatePopup();
}.bind(this));
html部分,地圖和popup的代碼截取,用了vue和element-ui實現綁定
<div style="height: 100%;">
<el-row style="height: 100%;">
<el-col :span="20" style="height: 100%;">
<el-row style="height: 100%;overflow: hidden;">
<!--地圖的div-->
<div class="mapContainer" id="mapDemo1"></div>
<!--地圖彈窗的html部分-->
<!--popupInfos是彈窗的數據源,其他跟一般的div沒區別-->
<!--PS:注意,要使popup不會超出地圖以外是通過父級div的overflow: hidden來實現-->
<div class="infoWindowItem" v-for="(popupInfo,index) in popupInfos" :style="popupInfo.style"
v-show="popupInfo.show">
<div class="item">
<span class="content">{{popupInfo.text}}</span>
</div>
</div>
</el-row>
</el-col>
實現效果,底圖是天地圖