OpenLayers 5 – How to Zoom View to Features in a Layer

openlayers

I'm adding a number of features (linestrings and points) to a layer and I want to zoom/pan the map view to the extent of those features.

I thought I'd have to do the following:

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
            }),
    ],
    target: 'map',
    view: new ol.View({
        center: ol.proj.fromLonLat([default_center_lon, default_center_lat]),
        maxZoom: 18,
        zoom: 7
    })
});

var features = []; 

// Add one or more features 

var marker = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([coordinatesLong, coordinatesLat])),
        });

features.push(marker);

var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: features
    })
});

map.addLayer(layer);

var layerExtent = layer.getExtent();

if (layerExtent) {
    map.getView().fit(layerExtent);
}

But the map remains at the default center and zoom level, instead of zooming/panning to the extent of the features.

Best Answer

The extent should be computed from the layer source, not from the layer itself.

var layerExtent = layer.getSource().getExtent();
Related Question