最近遇到的需求中需要对openlayer地图的一些事件进行监听,然后传递到高德、百度等原生地图中。 这个需求是因为openlayer的访问的xyz方式地图比较陈旧,一些地铁、小区的线路不一致,还是旧版本。 这里给大家分享一个解决方案: 把原生地图与openlayer地图进行重叠,并透明化openlayer地图,再传递openlayer的事件到原生地图。 var _mapEvent = function(event) { mapEvent(event); } var openlayerMap = new ol.Map({ layers: "定义的图层", loadTilesWhileInteracting: true, target: "目标div", view: new ol.View({ center: point, zoom: 13 }) }); // 地图移动、缩放事件 openlayerMap.on('moveend', _mapEvent); // 响应拖拽事件 openlayerMap.on('pointerdrag', _mapEvent);
function mapEvent(event) { var coordinate=map.getEventCoordinate(event); var coordinate=event.target.focus_; if (event.type == "pointerdrag"){ //拖拽地图平移 } if (event.type == "moveend") { //缩放 } }
使用openlayer自带的注册事件函数ol.map.on(‘click’,function(e))时,map.getEventCoordinate(event),返回的x、y都是NaN。
然而使用js或jquery的事件监听$("#map").click(function (e)时,map.getEventCoordinate(event),虽然能够获取x、y的值,支持的事件只有鼠标点击、移入、移除、悬停等,无法满足地图的拖拽、缩放的事件。
通过控制台调试,发现event.target.focus_可以获取当前焦点坐标,x、y。