Andy Nichols
Andy Nichols

Reputation: 3002

Zooming an OpenLayers3 map to cover multiple vector layers

I have an OpenLayers3 map consisting of an OSM Tile layer and one or more Vector layers. I can zoom the map into a single layer using

vector.addEventListener("change", function() {
    map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
});

and this works. However, if I try to zoom to cover multiple layers using the following in the loop that adds layers

vector.addEventListener("change", function () {
    if (bounds == null) {
        bounds = vectorSource.getExtent();
    } else {
        bounds = bounds.extend(vectorSource.getExtent());
    }
    map.getView().fitExtent(bounds, map.getSize());
});

with bounds being declared outside the loop, then maps with a single layer continue to work. However, with more than one layer, the code in the else block give the error "undefined is not a function".

According to the documentation getExtent() returns an extent object and the extent object has an extend method, so I'm not sure why this errors.

Upvotes: 3

Views: 1206

Answers (1)

Andy Nichols
Andy Nichols

Reputation: 3002

Answering own question as I worked it out. I was using extend wrongly. The correct code is:

vector.addEventListener("change", function () {
    if (bounds == null) {
        bounds = vectorSource.getExtent();
    } else {
        bounds = ol.extent.extend(bounds, vectorSource.getExtent());
    }
    map.getView().fitExtent(bounds, map.getSize());
});

Upvotes: 5

Related Questions