2

I had a look at this post: How to get all Vector layers from OpenLayers map?

The following construct is shown:

    map.getLayersByClass("OpenLayers.Layer.Vector") 

Unfortunately getLayersByClass is not recognised in this version of OpenLayers.

I add each of my vector layers here:

    if (!group.olSourceVector)
            group.olSourceVector = new ol.source.Vector({});

        if (!group.olLayerVector)
            group.olLayerVector = new ol.layer.Vector({ source: group.olSourceVector });

    this.olMap.addLayer(group.olLayerVector);

Then features are added to each LayerVector.

Just prior to drawing the map, I want to run through all the Layer Vectors to calculate the extent of the map.

2

The newer versions of OpenLayers allow you to get all map layers regardless of class name etc. with the map.getLayers() function. This function returns an ol.Collection object.

Take a look at the answer here, it's an older solution to the same problem as yours: https://stackoverflow.com/questions/30121024/openlayers-3-zoom-to-combined-extent

It's a little outdated now (map.getView().fitExtent has been renamed to .fit for example) so I've adapted the code for your scenario.

Given that you appear to be using groups, it's also necessary to include a check for whether or not the current layer is actually a group; and if it is, to loop through all sub-layers.

//Create an empty extent that we will gradually extend
var extent = ol.extent.createEmpty();

map.getLayers().forEach(function(layer) {
    //If this is actually a group, we need to create an inner loop to go through its individual layers
    if(layer instanceof ol.layer.Group) {
        layer.getLayers().forEach(function(groupLayer) {
            //If this is a vector layer, add it to our extent
            if(layer instanceof ol.layer.Vector)
                ol.extent.extend(extent, groupLayer.getSource().getExtent());
        });
    }
    else if(layer instanceof ol.layer.Vector)
       ol.extent.extend(extent, layer.getSource().getExtent());
});

//Finally fit the map's view to our combined extent
map.getView().fit(extent, map.getSize());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.