Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a click event on OpenLayers 4?

Tags:

gis

openlayers

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.

like image 442
user9370976 Avatar asked Dec 13 '22 23:12

user9370976


2 Answers

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.

like image 105
Sumanth Shastry Avatar answered Mar 13 '23 00:03

Sumanth Shastry


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 
  }
}); 
like image 37
René Avatar answered Mar 13 '23 02:03

René