在使用openlayers作为地图前端展示层的时候,用户经常需要点击具体某个feature之后弹出该feature的具体信息,因此封装一个弹出层组件作为公共组件,样式统一,调用简单。代码如下:
1、 组件封装
Popup.js
/*
刘玉峰 jjxliu306@163.com
2018-05-05
*/
//点击后高亮下方的feature 并且弹出popup信息做展示
Popup = function(map ){
this.map = map ;
//添加一个popup的div
var div = document.createElement("div");
div.id = 'popup';
div.className='ol-popup';
div.innerHTML = ' <a href="#" id="popup_closer" class="ol-popup-closer"></a> ' +
' <div id="popup_content"></div> ' ;
document.body.appendChild(div);
var overlay = new ol.Overlay({
element: div,
autoPan: true,
autoPanAnimation: {
duration: 250
}/* ,
offset:[0,-45]*/
});
map.addOverlay(overlay);
//扔到map里 后面方便调用
this.popup = overlay ;
document.getElementById('popup_closer').onclick = function() {
overlay.setPosition(undefined);
//$('#popup_closer').blur();
return false;
};
}
/**
* 泡泡显示信息
* @param _info 气泡内容
* @param _position 气泡显示的位置 [lon,lat]
*/
Popup.prototype.tooltip = function(_info , _position) {
document.getElementById('popup_content').innerHTML = _info ;
//设置popup的位置
this.popup.setPosition(_position);
}
样式popup.css
.ol-popup {
position: absolute;
background-color: white;
-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));
padding: 15px;
border-radius: 10px;
border: 1px solid #cccccc;
bottom: 12px;
left: -50px;
font: italic bold 12px ;
min-width: 280px;
}
.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;
}
.ol-popup-closer {
text-decoration: none;
position: absolute;
top: 2px;
right: 8px;
}
.ol-popup-closer:after {
content: "✖";
}
2、 测试,鼠标点击地图后弹出当前鼠标的点击位置信息 :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>openlayers-popup</title>
<link rel="stylesheet" href="ol.css" type="text/css">
<link rel="stylesheet" href="popup.css" type="text/css">
<style>
.map {
height: 500px;
width: 100%;
}
</style>
<script src="ol.js" type="text/javascript"></script>
<script src="popup.js" type="text/javascript"></script>
</head>
<body>
<h2>openlayers popup 工具封装测试 </h2>
<div id="map" class="map"></div>
<h2>刘玉峰 jjxliu306@163.com</h2>
<script type="text/javascript">
var osm = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
target: 'map',
layers:[osm],
view: new ol.View({
center: [ 120, 30],
zoom: 10,
projection: 'EPSG:4326'
})
});
var popup = new Popup(map);
//下面对鼠标点击时间进行监听
map.on('click', function(evt) {
var position = map.getEventCoordinate(evt.originalEvent);
popup.tooltip(position , position);
});
</script>
</body>
</html>
效果如下:
popup.png
码云代码地址:
https://gitee.com/jjxliu306/ol_extension/tree/master/tool/popup