一、定义popup弹窗dom对象
要展示弹窗,我们首先需要一个dom对象来承载。
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer" onclick="closePopup();"></a>
<div id="popup-title" class="popup-title"></div>
<div id="popup-content" class="popup-content"></div>
</div>
二、定义弹窗样式
在css文件中定义弹窗的样式。
.ol-popup {
display: none;
position: absolute;
background-color: white;
-moz-box-shadow: 0 1px 4px rgba(0,0,0,0.2);
-webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
width: 200px;
}
.ol-popup:after, .ol-popup:before {
top: 100%;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.ol-popup:after {
border-top-color: white;
border-width: 10px;
left: 48px;
margin-left: -10px;
}
.ol-popup:before {
border-top-color: #cccccc;
border-width: 11px;
left: 48px;
margin-left: -11px;
}
.popup-title{
font-weight: bold;
border-bottom:1px solid #cccccc;
padding: 5px 8px;
}
.popup-content{
padding: 5px 8px;
}
.ol-popup-closer {
text-decoration: none;
position: absolute;
top: 6px;
right: 6px;
}
.ol-popup-closer:after {
content: "✖";
}
三、定义Overlay
声明一个Overlay,为它绑定前面创建的dom对象,将其加进Map。
var overlay = new ol.Overlay({
element: document.getElementById('popup'), //绑定dom对象,纯js必须使用document绑定,不能像Map的dom对象,只写‘popup’
autoPan: true, //点击地图边缘时,地图自动调节
autoPanMargin: 20,
positioning: 'center-center'
});
map.addOverlay(overlay);
四、设置单击地图后弹窗显示信息
设置当在地图上左键单击时,弹窗显示所点击的点的经纬度信息。
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var title = document.getElementById('popup-title');
var closer = document.getElementById('popup-closer');
map.on("singleclick", function (evt) {
var coordinate = evt.coordinate; // 获取坐标
var hdms = ol.coordinate.toStringHDMS(ol.proj.toLonLat(coordinate)); // 转换坐标格式
console.log(hdms);
overlay.setPosition(coordinate);
content.innerHTML = '<p>You clicked here:</p><code>' + hdms +
'</code>'; //弹窗展示内容为经纬度信息
container.style.display = 'block';
title.innerHTML = "提示信息";
title.style.display = 'block';
});
五、设置弹窗关闭事件
为弹窗右上角的关闭按钮设置关闭事件函数
function closePopup() {
// 把弹窗位置设置为undefined,并清空坐标数据
overlay.setPosition(undefined);
document.getElementById("popup-closer").blur();
return false;
}
最终效果如下: