openlayers上添加点击事件
有很多场景会有这个需求,就是我绘制了图标,点击图标需要展示一些对应的信息
openlayer的事件主要是通过监听来完成的,你所有的icon的点击事件都是可以通过监听map的点击事件来处理对应的逻辑的
话不多说直接上代码
// 监听singleclick事件,通过点击事件,获取对应点的feature图标 const that: any = this; var overlay: any var popupCloser = document.getElementById("popup-closer") as HTMLElement; that.map.on('singleclick', function (e: any) { var container = document.getElementById("popup") as HTMLElement; var content = document.getElementById("popup-content") as HTMLElement; overlay = new olOverlay({ //设置弹出框的容器 element: container, //是否自动平移,即假如标记在屏幕边缘,弹出时自动平移地图使弹出框完全可见 autoPan: true }); console.log(e.coordinate) if (that.map.hasFeatureAtPixel(e.pixel)) { var feature = that.map.getFeaturesAtPixel(e.pixel) console.log(feature) var pixel = that.map.getEventPixel(e.originalEvent); that.map.forEachFeatureAtPixel(pixel, function (feature: any) { //coodinate存放了点击时的坐标信息 var coodinate = e.coordinate; //设置弹出框内容,可以HTML自定义 content.innerHTML = "<p>你点击的坐标为:" + coodinate + "</p>"; //设置overlay的显示位置 overlay.setPosition(coodinate); //显示overlay that.map.addOverlay(overlay); }); } }) popupCloser.addEventListener('click', function () { overlay.setPosition(undefined); });
你会发现里面很多dom的操作方式,没错,openlayer就是这么强大,就是你所有的渲染等都是对应的一个dom,就是div这种,不想pixijs等是通过canvas去绘制的
在此之前你还需要在你html里添加对应的dom元素,如下
<template> <div class="main"> <div id="map" class="map"> <div id="mouse-position"></div> </div> <div id="popup" class="ol-popup"> <a href="#" id="popup-closer" class="ol-popup-closer"></a> <div id="popup-content"></div> </div> </div> </template>
顺表丢上css样式,哈哈
.ol-popup {
position: absolute;
background-color: #eeeeee;
-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;
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: #eeeeee;
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: "✖";
}
接下来看看效果
索嘎,点击事件完工