简体   繁体   中英

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.

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());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM