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.