有不少場景會有這個需求,就是我繪製了圖標,點擊圖標須要展現一些對應的信息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