openlayer4 弹出框封装 博客分类: GIS openlayerspopuptootip地图
程序员文章站
2024-02-25 08:41:46
...
很多场景需要在地图上弹出一个tooltip或者popup之类的小窗口显示一些信息,最近简单做了一下封装,方便后续调用,代码如下:
/* 刘玉峰 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); }
需要引入一个样式文件:
.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>
效果如图:
公网的案例:
http://47.98.238.202:8000/ol_extension/tool/popup/
码云代码地址:
https://gitee.com/jjxliu306/ol_extension/tree/master/tool/popup