1

Using Openlayers.....Is it possible to select a feature on a map by an attribute? eg: Select a feature from a dropdown menu populated with the feature "id" or a table field attribute values.

1
  • Have you looked at CQL filters? Commented Jun 20, 2013 at 3:07

2 Answers 2

2

You can either use the getFeaturesByAttribute method, or loop through the layer's features array:

for(var f=0;f<layer.features.length;f++) {
  if(layer.features[f].attributes.someAttribute == 'desiredValue') {
    selectFeatureControl.select(layer.features[f]);
    break;
  }
}

This assumes you have an active instance of OpenLayers.Control.SelectFeature named "selectFeatureControl", a vector layer named "layer" and you are looking for feature having someAttribute loosely equal to 'desiredValue'. If you have to consider not only the value but also data type (as getFeaturesById does), replace == with ===.

4
  • Very good, Just something I cant get my head around. Do I have the function with the "for" loop outside the map init function? If so how do I reference the layer as it returns "undefined" I have onClick=functionnamehee(fidvalue, layername, selectname)
    – Haydlew
    Commented Jun 21, 2013 at 0:19
  • Pressed enter by mistake :( , Where should the function run?? Currently, I have a button onClick=selectfeatureA(234, 'farmpaddocks', 'selectA') Then as an js file function I have:<pre> function selectfeatureA(fidvalue,layername, selname) { for(var f=0;f<layername.features.length;f++) { if(layername.features[f].attributes.fid == value) { selname.select(layername.features[f]); break; }}}<code> My apologies, I'm obviously not an experienced coder.
    – Haydlew
    Commented Jun 21, 2013 at 0:33
  • Yes, it's better (from the terminally lazy programmer's point of view) to have the search function (and layer declarations too) outside map init function. If you don't want to have layers as global variables, then use map.getLayersBy() or map.getLayersByName() to reference the layer. Please note that these methods return arrays, so you will have to extract the layer instance like this: var layer = map.getLayersByName('farmpaddocks')[0] Commented Jun 21, 2013 at 6:47
  • Perfect, thank you very much Michal. map.getLayersByName('farmpaddocks')[0] Worked great!!.
    – Haydlew
    Commented Jun 25, 2013 at 4:10
1

Of course. You can get feautures using getFeaturesByAttribute method and redraw them using drawFeature.

1
  • I only need to highlight or select the feature from a table ... not redraw the single feature. Here is a great example. link[link] I can pass the fid to a function fine, but I want to know if I can select the feature where farmpaddock.fid = fid. Hope that makes more sense.
    – Haydlew
    Commented Jun 20, 2013 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.