[GIS] Openlayers 2: Check the map content and tell if the feature exists in the map bound

openlayers-2

In my map there are a number of layers. I want my custom legends to show when the related layer feature is visible in the current map view. I am able to turn on/off the display of the legend according to display scale but I need to hide the legend if the feature is not in the map view even if it is in the range of display scale.

I go through the layer collection of the map. I tried to debug when the vector layer feature is visible in the map view but I get layer.features.length as always zero.

I need it total in terms of openlayers script. I do not want to utilize GeoExt.

Best Answer

Here's a way to determine whether a feature is visible in the current extent:

features = your-layer.features; 
for (var i = 0; i < features.length; i++) { 
    if (features[i].geometry.getBounds().intersectsBounds(map.getExtent())) { 
        console.log(features[i]); 
    } 
}