Openlayers 3: Select a feature programmatically
Asked Answered
W

3

19

I am trying to upgrade my system from Openlayers 2 to Openlayers 3 and I have having one particular issue that I cannot seem to figure out.

My application has a grid and a map and when a user clicks on the grid I want to select the relevant point on the map.

In Openlayers 2 I used the following:

self.selectControl.select(feature[0]);

I cannot find or understand how to do the same in Openlayers 3.

So to be clear, I have a feature which I have found programmatically and I want to select that feature on a map (programmatically)!

I cannot seem to find anything in the APIs but that might be due to my lack of understanding as I am new to Openlayers.

Wesleywesleyan answered 17/10, 2014 at 10:2 Comment(0)
W
28

To do this you need to do the following:

mySelectControl.getFeatures().clear() -> removes the selected items

mySelectControl.getFeatures().push(featureToSelect) -> selects the applied feature
Wesleywesleyan answered 17/10, 2014 at 10:8 Comment(2)
@bebraw - I will when StackOverflow will let me, says I have to wait another hour (from time of writing)Wesleywesleyan
Thanks for that. It's far from obvious in any of the official documentation or any of the examples I've found, that you can push() to the getFeatures() array. [Yeah, I know, it's inherent in the definition of ol.Collection, but that's only obvious in hindsight]Encouragement
D
11
var selectInteraction = new ol.interaction.Select(}); 
map.addInteraction(selectInteraction);

function highlightFeature(feat){
   selectInteraction.getFeatures().push(feat);
   selectInteraction.dispatchEvent({
      type: 'select',
      selected: [feat],
      deselected: []
   });
}

works like a char on latest openlayers 4.5

Draghound answered 4/12, 2017 at 23:33 Comment(0)
G
2
  1. Add a select interaction to your map.

    var selectInteraction = new ol.interaction.Select();
    map.addInteraction(selectInteraction);
    
  2. Add any features you want to select to the select interaction's feature array.

    selectInteractions.getFeatures().push(featureToSelect);
    
Greenroom answered 28/9, 2016 at 16:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.