本文介绍了使用弹出窗口在 OpenLayers 5 上动态显示多个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在我已经保存在数组中的地图上显示两个标记.我希望标记动态显示,并且每个标记都有一个弹出窗口.这是我从我的最后一个问题中编写和编辑的代码.我在地图上什么也没显示,有人能解决这个问题吗?,我尝试了很多东西,但似乎没有任何效果.我真的是地图的新手.
I am trying to display two Markers on the Map which i already saved in an array. I want the Markers to be dynamically displayed and with a Pop-up window for each one.here is the code i wrote and edited from my Last question. I get nothing displayed on the Map, can somebody fix the problem?, I have tried many things but nothing seems to be working.I am really newbie to Maps.
/* open street map newest version */
var map = new ol.Map({
target: 'map', // the div id
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([4.35247, 52.520008]),
zoom: 6,
minZoom: 3
})
});
//create an empty vectorSrc
var vectorSource = new ol.source.VectorSource();
var layer = new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
image: new ol.style.Icon({
src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png', //
scale: 0.4 // set the size of the vehicle on the map
})
})
});
for(var i=0; i < arrayPos.length; i++) {
var long = arrayPos[i][0]
var lat = arrayPos[i][1];
var batteryCharge = arrayPos[i][3];
// create a new feature with the positon values from the array
var feature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([long, lat]))
})
//Batterycharge value is going to be printed in the Pop-up window
feature.set('batteryCharge', batteryCharge);
vectorSource.add(feature);
}
map.addLayer(layer);
//initialize the popup
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
map.addOverlay(overlay);
//display the pop with on mouse over event
map.on('pointermove', function (event) {
if (map.hasFeatureAtPixel(event.pixel) === true) {
var coordinate = event.coordinate;
const features = event.target.getFeatures();
const batteryCharge = features.get(0).get('batteryCharge');
//simple text written in the popup, values are just of the second index
content.innerHTML = event.traget+'<br><b>Batteriestatus: </b>'+batteryCharge;
overlay.setPosition(coordinate);
}
else {
overlay.setPosition(undefined);
}
});
推荐答案
event.target.getFeatures()
用于选择交互.对于地图上的 pointermove
尝试替换
event.target.getFeatures()
is used for select interactions. For pointermove
on a map try replacing
if (map.hasFeatureAtPixel(event.pixel) === true) {
var coordinate = event.coordinate;
const features = event.target.getFeatures();
const batteryCharge = features.get(0).get('batteryCharge');
与
const features = map.getFeaturesAtPixel(event.pixel);
if (features.length > 0) {
var coordinate = event.coordinate;
const batteryCharge = features[0].get('batteryCharge');
这篇关于使用弹出窗口在 OpenLayers 5 上动态显示多个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!