OpenLayers – How to Fit Map View to a Layer Extent in OpenLayers 5

javascriptopenlayers

I added a number of markers to the map:

const map = new ol.Map({
    target: 'map',
    layers: [
        new Layer.Tile({source: new OSM()}),
        markersVector,
    ],
    view: new ol.View({
        center: [0, 0],
        zoom: 2,
    })
});

// ...

let setMarkers = function (markers) {
    let features = markers.map((marker) => createFeature(...marker));
    markerSource.addFeatures(features);

    // how to fit?
};

setMarkers(window.markers || []);

After adding the features I would like the map to zoom as much as possible so that all markers are visible at once. How to do that? Previous versions had a zoomToExtent method which is now missing, obviously.

I tried the map.getView().fit(...) method with various inputs, but I didn't manage. The view stays fixed to such location:

View fixed location

I tried, but it does not do anything:

map.getView().fit(
    map.getView().calculateExtent(),
    {constrainResolution: false, padding: [10, 10, 10, 10]}
);

Edit:

The map.getView().calculateExtent() returns the same extent initially and after adding the features. So I guess my question is how to calculate the extent properly.

Best Answer

This was as easy as:

const markerSource = new source.Vector();

//...

map.getView().fit(markerSource.getExtent());
Related Question