how to hide vector features in openlayers

Andrew Christensen picture Andrew Christensen · Jun 30, 2011 · Viewed 22.2k times · Source

I have written some code to hide specific markers in our maps based on checkboxes outside of the map itself. However, these markers also have vector features too (really on separate layers) but I want to just hide the features rather than destroy them. I tried using display(false) but get errors. Is there a function for hiding vectors?

Answer

igorti picture igorti · Jul 1, 2011

Solution

Change the style property for OpenLayers.Feature.Vector instances. Set the display attribute to none or the visibility attribute to hidden. Redraw the layer afterwards.

According to comments in OpenLayers code:

display - {String} Symbolizers will have no effect if display is set to "none". All other values have no effect.

Example Code

For a given OpenLayers layer variable called layer, you could hide all the features as follows:

var features = layer.features;

for( var i = 0; i < features.length; i++ ) {
  features[i].style = { visibility: 'hidden' };
}

layer.redraw();

This iterates over all features in a layer, allowing full control of the specific features to hide.