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.
JavaScript
x
72
72
1
/* open street map newest version */
2
var map = new ol.Map({
3
target: 'map', // the div id
4
layers: [
5
new ol.layer.Tile({
6
source: new ol.source.OSM()
7
})
8
],
9
view: new ol.View({
10
center: ol.proj.fromLonLat([4.35247, 52.520008]),
11
zoom: 6,
12
minZoom: 3
13
})
14
});
15
16
//create an empty vectorSrc
17
var vectorSource = new ol.source.VectorSource();
18
19
var layer = new ol.layer.Vector({
20
source: vectorSource,
21
style: new ol.style.Style({
22
image: new ol.style.Icon({
23
src: 'https://wiki.openstreetmap.org/w/images/0/0c/Hgv.png', //
24
scale: 0.4 // set the size of the vehicle on the map
25
})
26
})
27
});
28
for(var i=0; i < arrayPos.length; i++) {
29
var long = arrayPos[i][0]
30
var lat = arrayPos[i][1];
31
var batteryCharge = arrayPos[i][3];
32
33
// create a new feature with the positon values from the array
34
var feature = new ol.Feature({
35
geometry: new ol.geom.Point(ol.proj.fromLonLat([long, lat]))
36
})
37
38
//Batterycharge value is going to be printed in the Pop-up window
39
feature.set('batteryCharge', batteryCharge);
40
vectorSource.add(feature);
41
}
42
map.addLayer(layer);
43
44
//initialize the popup
45
var container = document.getElementById('popup');
46
var content = document.getElementById('popup-content');
47
48
var overlay = new ol.Overlay({
49
element: container,
50
autoPan: true,
51
autoPanAnimation: {
52
duration: 250
53
}
54
});
55
map.addOverlay(overlay);
56
57
//display the pop with on mouse over event
58
map.on('pointermove', function (event) {
59
if (map.hasFeatureAtPixel(event.pixel) === true) {
60
var coordinate = event.coordinate;
61
const features = event.target.getFeatures();
62
const batteryCharge = features.get(0).get('batteryCharge');
63
64
//simple text written in the popup, values are just of the second index
65
content.innerHTML = event.traget+'<br><b>Batteriestatus: </b>'+batteryCharge;
66
overlay.setPosition(coordinate);
67
}
68
else {
69
overlay.setPosition(undefined);
70
}
71
});
72
Advertisement
Answer
event.target.getFeatures()
is used for select interactions. For pointermove
on a map try replacing
JavaScript
1
5
1
if (map.hasFeatureAtPixel(event.pixel) === true) {
2
var coordinate = event.coordinate;
3
const features = event.target.getFeatures();
4
const batteryCharge = features.get(0).get('batteryCharge');
5
with
JavaScript
1
5
1
const features = map.getFeaturesAtPixel(event.pixel);
2
if (features.length > 0) {
3
var coordinate = event.coordinate;
4
const batteryCharge = features[0].get('batteryCharge');
5