1. 程式人生 > >基於openlayer4打點,點選點位彈出窗

基於openlayer4打點,點選點位彈出窗

// 初始給的中心點座標。 var centerX = 117.3626; var centerY = 32.9184; // 我們需要一個vector的layer來放置圖示 var layer = new ol.layer.Vector({ source : new ol.source.Vector() }) var map = new
ol.Map({ layers : [ new ol.layer.Tile({ // 載入網際網路地圖 source : new ol.source.OSM() }), layer ], target : 'map', view : new ol.View({ projection : 'EPSG:4326'
, center : [ 117.204883, 31.840285 ], zoom : 10 }) }); var lnglats = [ [117.204883, 31.840285], [117.2616140654, 31.8626171434], [117.2870114613, 31.8588879936
], [117.2822851546, 31.8862905440] ]; // 建立一個Feature,並設定好在地圖上的位置 var anchor = new ol.Feature({ geometry : new ol.geom.Point(lnglats[0]) }); // 設定樣式,在樣式中就可以設定圖示 anchor.setStyle(new ol.style.Style({ image : new ol.style.Icon({ src : 'img/1_03.png' }), //anchor: [0.5, 1] // 設定圖示位置 })); // 新增到之前的建立的layer中去 layer.getSource().addFeature(anchor); // 彈出窗容器DIV var container = document.getElementById("popup"); // 彈出窗內容DIV var content = document.getElementById("popup-content"); // 彈出窗關閉 var popupCloser = document.getElementById("popup-closer"); var overlay = new ol.Overlay({ //設定彈出框的容器 element : container, //是否自動平移,即假如標記在螢幕邊緣,彈出時自動平移地圖使彈出框完全可見 autoPan : true, autoPanAnimation : { duration : 250 //當Popup超出地圖邊界時,為了Popup全部可見,地圖移動的速度. } }); // openlayer4只有針對整個地圖事件監聽,可以通過以下方式達到對feature監聽,也可對feature自定義點選事件。 map.on('click', function(e) { //在點選時獲取畫素區域 var pixel = map.getEventPixel(e.originalEvent); map.forEachFeatureAtPixel(pixel, function(feature) { //coodinate存放了點選時的座標資訊 var coodinate = e.coordinate; console.log(coodinate); //設定彈出框內容,可以HTML自定義 content.innerHTML = coodinate; //設定overlay的顯示位置 overlay.setPosition(coodinate); //顯示overlay map.addOverlay(overlay); }); }); popupCloser.addEventListener('click', function() { overlay.setPosition(undefined); }); /** * 為map新增滑鼠移動事件監聽,當指向標註時改變滑鼠游標狀態 */ map.on('pointermove', function (e) { var pixel = map.getEventPixel(e.originalEvent); var hit = map.hasFeatureAtPixel(pixel); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; })