My .html:
<div id="map"></div>
<div id="popup" class="ol-popup">
<a href="#" id="popup-closer" class="ol-popup-closer"></a>
<div id="popup-content"></div>
</div>
My .js
var attribution = new ol.control.Attribution({
collapsible: false
});
var map = new ol.Map({
controls: ol.control.defaults({ attribution: false }).extend([attribution]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
//url: 'https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png'
})
})
],
target: 'map',
view: new ol.View({
//Center map to producing office address
center: ol.proj.fromLonLat([-76, 45]),
zoom: 2.75
})
});
var CircleStyle = ol.style.Circle
var {Fill, Icon, Stroke, Style} = ol.style;
var styles = {
'greenCircle': new Style({
image: new CircleStyle({
radius: 7,
stroke: new Stroke({
color: 'green',
width: 5,
}),
}),
}),
'yellowCircle': new Style({
image: new CircleStyle({
radius: 7,
stroke: new Stroke({
color: 'yellow',
width: 5,
}),
}),
}),
'redCircle': new Style({
image: new CircleStyle({
radius: 7,
stroke: new Stroke({
color: 'red',
width: 5,
}),
}),
}),
};
var Can = new ol.Feature({
type: 'greenCircle',
geometry: new ol.geom.Point(ol.proj.fromLonLat([-79, 44]))
, id: 1
});
var Ger = new ol.Feature({
type: 'yellowCircle',
geometry: new ol.geom.Point(ol.proj.fromLonLat([13, 53]))
, id: 2
});
var Chn = new ol.Feature({
type: 'redCircle',
geometry: new ol.geom.Point(ol.proj.fromLonLat([116, 40]))
, id: 3
});
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
features: [Can, Ger, Chn]
}),
style: function (feature) {
return styles[feature.get('type')];
}
});
map.addLayer(layer);
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
var overlay = new ol.Overlay({
element: container,
autoPan: true,
autoPanAnimation: {
duration: 250
}
});
map.addOverlay(overlay);
closer.onclick = function () {
overlay.setPosition(undefined);
closer.blur();
return false;
};
map.on('singleclick', function (event) {
if (map.hasFeatureAtPixel(event.pixel) === true) {
var coordinate = event.coordinate;
content.innerHTML = '<b style="color:black;">Canada:</b><br/><a href="program.html#Canada" style="color:blue;">Policy Details</a><br/><a href="service.html" style="color:blue;">Service Details</a>';
overlay.setPosition(coordinate);
} else {
overlay.setPosition(undefined);
closer.blur();
}
});
The above code successfully shows three different colored circles on a map and the same popup for each when the user clicks on the circles. The problem is I want to show different popups for each circle when the user clicks on them. I am using Openlayers 5. Appreciate any help. Thanks!
You will need to determine which feature is at the clicked pixel, and display content based on the properties of that feature: