I need to attach an event listener to a feature in OpenLayers 4. I've tried the feature.on('click',function(){...}) but it is not working. How can i add tan event to a feature? Thank you in advance.
There is no click
event registered for a feature ol.Feature
object. But click
event is present for ol.Map
. Use forEachFeatureAtPixel
method to get all the features at a pixel and compare it with the feature for which you want to add a listener.
Relevant Code :
var featureListener = function ( event ) {
console.log("featureListenerCalled");
alert("Feature Listener Called");
};
map.on('click', function(event) {
map.forEachFeatureAtPixel(event.pixel, function(feature,layer) {
if ( feature.getId() == "IND" ) {
feature.setStyle(listenerStyle);
featureListener(event);
}
});
});
I have created this pluckr link which demonstrates this. Click on India map.
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([lon, lat])),
adres: adres
//population: 4000,
//rainfall: 500
});
// iconFeatureA is an array that gets all features on mouse click pixel location
map.on('click', function(e) {
var iconFeatureA = map.getFeaturesAtPixel(e.pixel);
if (iconFeatureA !== null) {
var adres = iconFeatureA[0].get("adres");
alert(adres);
e.preventDefault(); // avoid bubbling
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With