[GIS] Selecting Feature by attribute OpenLayers

kmlopenlayers

I'm attempting to limit the features on a vector layer by searching by some attribute (preferably name). I've managed to get the array of features but cannot seem to work out how to iterate over them until I find one with a specified name.

I saw in earlier versions of OpenLayers there were functions like getFeatureByAttribute which could help but there doesn't seem to be anything like this any more.

Best Answer

If you're using a vector layer with a vector source, getting a specific feature by any of its attributes is easy.

var vectorSource = vectorLayer.getSource();
var features = vectorSource.getFeatures();
var value = 'foo';
var property = 'name';
var found;
for (var i = 0, ii = features.length; i < ii; i++) {
  if (features[i].get(property) === value) {
    found = features[i];
    break;
  }
}
console.log(found);

Feel free, as part of your projet, to create your own util method to accomplish this.