Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openlayers 3: Select a feature programmatically

Tags:

openlayers-3

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.

like image 773
Scott Sellers Avatar asked Oct 17 '14 10:10

Scott Sellers


3 Answers

To do this you need to do the following:

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

mySelectControl.getFeatures().push(featureToSelect) -> selects the applied feature
like image 151
Scott Sellers Avatar answered Nov 12 '22 08:11

Scott Sellers


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

like image 25
Fuad All Avatar answered Nov 12 '22 08:11

Fuad All


  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);
    
like image 43
JellyRaptor Avatar answered Nov 12 '22 07:11

JellyRaptor