[GIS] Openlayers – Get extent of WFS vector layer and zoom to that extent when map

extentsopenlayers-2wfs

I would like to do the following:

1) While loading an OpenLayers map object get the lat/long Bounding Box of a WFS vector layer served from GeoServer.
2) Use the extent from the WFS vector layer to zoom so the entire layer is viewable.

This is the script I have now that uses the lat/longs from the WFS vector and then zooms. This script works fine. I have a javascript function where the map and controls are created in the onLoad of the html Body tag. At the end of the script I call the loadZoomTo() function which then calls this line of script;

function zoomOnLoad() {
    this.map.setCenter(new OpenLayers.Bounds(-79.8961,41.1,-78.80809,42.2).getCenterLonLat(), 10);  
}

In this script I have the lat/longs hard-coded but I need to be able to change these interactively depending on what option the user selects when he enters the application. If I remove the hard-coded lat/longs and try to replace them with something like this:

function zoomOnLoad() {
this.map.setCenter(new OpenLayers.Bounds(mLayers[a].getDataExtent()).getCenterLonLat(), 0);
}

it fails. I have also tried the event handler method as detailed here: OpenLayers, zoom to vector layer extent

but all I get is the html of the page with none of the OpenLayers stuff. No map, no controls etc..

Any suggestions would be appreciated.

Best Answer

After struggling with it for about 6 hours I was able to get it to work. Here is the script I used to solve the problem:

lyrstands = new OpenLayers.Layer.Vector("Stands 1stQ 2012",
{ 
    strategies: [new OpenLayers.Strategy.BBOX()],
    eventListeners: {           
        'loadend': function (evt) {//THE LOADEND EVENT LISTENER - WHEN THE LAYER IS DONE LOADING...
            map.zoomToExtent(lyrstands.getDataExtent());//ZOOM TO ITS EXTENT!
            }//END OF THE LOADEND EVENT
    },//END OF THE eventListeners BLOCK
    protocol: new OpenLayers.Protocol.WFS({
        url: "/geoserver/wfs",
        featureType: "Stands_1stQ2012",
        featureNS: "http://000.000.000.000:8080/OH_Layers",
        geometryName: "the_geom",
        version: "1.1.0"
    })
});
Related Question