3

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.

1 Answer 1

6

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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