[GIS] Using OpenLayers 3 Feature onclick event

cartographyjavascriptopenlayers

I looked for a way to fire onclick event and I found Adding event handler to feature in OpenLayers 3? at Stack Overflow. I undestand from this question is that there is no event onclick to features. I want to understand why is it? And maybe there is upcoming to the API and they have added a click events.

the way they offered to do it is like that:

map.on("click", function(e) {
    map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
        //do something
    }
}

It means i need to fire a click on the whole div map, then look for my specificPixel that the feature contains and then do whatever i want. It sounds primitive and will take too long for a high amount of features.

Is there another way to solve this problem?

Secondly, as i see there is no that much events on OpenLayers 3 api .
Why is it?

Best Answer

It means i need to fire a click on the whole div map, then look for my specificPixel that the feature contains and then do whatever i want.

I don't think you understand how forEachFeatureAtPixel works. Once you click, it takes the pixel clicked and iterate through all the layers to find any feature within a range of that pixel coordinate. It's not going through all the pixels of the map. Look at the code to better understand this. Further, it doesn't even iterate through "ALL" the features, it finds the features which are currently visible in the frame state. Alternatively, if you have too many features, You can divide your features to few layers and apply a layer filter too

There is another way to solve this problem?

Yes, you can add a select interaction to the map and use 'add' event on its feature collection.

var select_interaction = new ol.interaction.Select();

select_interaction.getFeatures().on("add", function (e) { 
     var feature = e.element; //the feature selected
});

map.addInteraction(select_interaction);