7

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.

user9370976
  • 157
  • 1
  • 2
  • 13

2 Answers2

16

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.

Sumanth Shastry
  • 1,139
  • 1
  • 19
  • 28
2
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 
  }
}); 
René
  • 89
  • 1
  • 3