[GIS] zoom to extent of several vector layers

javascriptopenlayers-2

I'm trying to zoom to the extent of several vector layers data.

I've tried to create a new OpenLayers.Bounds bounds and to add a 'loadend' for each OpenLayers.Layer.Vector to increase bounds, but then I don't know where to put map.zoomToExtent(bounds)… is there a way to run this after all the layers have been loaded?

I've tried https://gis.stackexchange.com/a/6297, but it did not work, as the vector layers were not created yet…

I've also tried https://gis.stackexchange.com/a/41588/16356, but it did not work either, as I have several layers.

EDIT: Here is how I fixed the issue, thanks to Vadim.

bounds = new OpenLayers.Bounds();
map = new OpenLayers.Map('map');
LOADED_LAYERS = 0;

layers[1] = new OpenLayers.Layer.Vector("layer1", {
                eventListeners: {
                    'loadend': function (evt) {
                        LOADED_LAYERS++;
                        bounds.extend(layers[1].getDataExtent());
                        if (LOADED_LAYERS == 3) {
                            map.zoomToExtent(bounds);
                        };
                    }
                }
            });
layers[2] = ...;
layers[3] = ...;

map.addLayers(layers);
map.zoomIn();

Best Answer

This is not really a GIS question, but more of a basic logic/algorithm. Figure out a scheme to track that all of your layers are loaded and then run the map.zoomToExtent. It's a simple as that.

Do you know a list of layers that'll be added ahead of time (via code) or not (via some layer UI)? Do you know the names? or the number of layers?

Create an array and keep track of what has loaded (after every loadEnd fires). Go through the array, every time, and check "ok, did all my guys report in or is something still outstanding?". Once all layers are done, then zoom.

Or you can zoom to max extent Every single time a layer is added, but all you'll get is your map jumping around to bigger and bigger extent. .... Unless that's what you want.