Is there an event for when features are selected in OpenLayers 3?
Asked Answered
O

3

6

http://ol3js.org/en/master/examples/select-features.html

Given the above examples, what extension points are there for hooking into when features are selected?

Osrock answered 3/5, 2014 at 23:10 Comment(0)
P
2

You can bind a precompose event to your layer when a singleclick event is triggered on your map. From here you can dispatch a change event on your select interaction.

yourmap.on('singleclick',function(event)){
    layer.once('precompose',function(event){
        yourSelectInteraction.dispatchChangeEvent();
    }
}

yourSelectInteraction.on('change',function(){
    //Do stuff with your selected features here
}
Permenter answered 8/6, 2014 at 21:28 Comment(1)
Thanks, +1. Do you know why the change event is not dispatched automatically every time a feature is (un)selected ??Barrio
B
9

Here is a solution that might be more intuitive than Danny's, and also seems to be the "official" way, see this issue on ol3's GitHub.

Simply add the listener to the collection of selected features :

    mySelectInteraction.getFeatures().on('change:length', function(e) {
        if (e.target.getArray().length === 0) {
            alert("no selected feature");
        } else {
            var feature = e.target.item(0);
            alert(feature.getId()); //or do something better with the feature !
        }
    });
Barrio answered 24/9, 2014 at 15:36 Comment(2)
As mentioned in the GitHub issue, you can also subscribe to the 'add' and 'remove' events on the features collection.Suboxide
You can use e.target.getLength() instead of e.target.getArray().lengthThomasinathomasine
P
2

You can bind a precompose event to your layer when a singleclick event is triggered on your map. From here you can dispatch a change event on your select interaction.

yourmap.on('singleclick',function(event)){
    layer.once('precompose',function(event){
        yourSelectInteraction.dispatchChangeEvent();
    }
}

yourSelectInteraction.on('change',function(){
    //Do stuff with your selected features here
}
Permenter answered 8/6, 2014 at 21:28 Comment(1)
Thanks, +1. Do you know why the change event is not dispatched automatically every time a feature is (un)selected ??Barrio
L
0

You want to use the featureselected event handler:

This example is on a Vector layer:

featuresLayer.events.on({
    'featureselected': function (e) {
        console.log(e);
    }
});
Lunula answered 7/5, 2014 at 22:46 Comment(1)
is that openlayers 3? events is not defined.Solidstate

© 2022 - 2024 — McMap. All rights reserved.