很多场景需要在地图上弹出一个tooltip或者popup之类的小窗口显示一些信息,最近简单做了一下封装,方便后续调用,代码如下:
/* 刘玉峰 [email protected] 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 = ' ' + ' ' ; 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); }
需要引入一个样式文件:
.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、测试,鼠标点击地图后弹出当前鼠标的点击位置信息 :
openlayers-popup openlayers popup 工具封装测试
刘玉峰 [email protected]
效果如图:
公网的案例:
http://47.98.238.202:8000/ol_extension/tool/popup/
码云代码地址:
https://gitee.com/jjxliu306/ol_extension/tree/master/tool/popup