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.
2 Answers
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 ===.
-
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)– HaydlewCommented 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.– HaydlewCommented 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!!.– HaydlewCommented Jun 25, 2013 at 4:10
Of course. You can get feautures using getFeaturesByAttribute method and redraw them using drawFeature.
-
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.– HaydlewCommented Jun 20, 2013 at 5:43