OpenLayers: How to Zoom Map to Fit Selected Features Efficiently

openlayers

In my openlayers based application, I need to trigger zoom when user selects features so that all the selected features fit within the map extent.

I make use of this code:

map.getView().fit([swLong, swLat, neLong, neLat], map.getSize());

(swLong, swLat) is the south-west corner and (neLong, neLat) is the north-east corner of bounding box containing the selected features. These are in degrees.

What I am not sure is whether I need to provide these in pixels or degrees is the correct way?

Best Answer

The extent should be in view coordinates. The way you have specified size is correct for OpenLayers 3. For OpenLayers 4 and 5 the size defaults to map size so you don't need to specify it, but if you do I've included the OL4/5 syntax

map.getView().fit(ol.proj.transformExtent([swLong, swLat, neLong, neLat], 'EPSG:4326', map.getView().getProjection()), { size: map.getSize() });
Related Question