有不少场景会有这个需求,就是我绘制了图标,点击图标须要展现一些对应的信息css
openlayer的事件主要是经过监听来完成的,你全部的icon的点击事件都是能够经过监听map的点击事件来处理对应的逻辑的html
话很少说直接上代码web
// 监听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去绘制的canvas
在此以前你还须要在你html里添加对应的dom元素,以下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样式,哈哈this
.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: "✖"; }
接下来看看效果spa
索嘎,点击事件完工code