1

Is there a way to calculate zoom for given bounding box and map size in OpenLayers?

What I can do is fitting the map and then reading the zoom from view but I need to calculate it without setting the map:

map.getView().fit(
    ol.proj.transformExtent(
      ol.extent.boundingExtent(boundingBox),
      ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857')
    ), {
      size: map.getSize()
    }
  );

then I have the zoom by:

map.getView().getZoom()

I'd like something like:

function calcZoom(boundingBox, map.getSize()) { ... }
3
  • You can fit to a different view which is not part of any map.
    – Mike
    Dec 23, 2022 at 0:22
  • The zoom level is different for same bounding box on different map sizes (e.g. 300px,500px vs 500px,300px).
    – Martin
    Dec 23, 2022 at 0:33
  • 1
    You can use map.getView().getZoomForResolution(map.getView().getResolutionForExtent(extent, size)).
    – TomazicM
    Dec 23, 2022 at 10:04

1 Answer 1

1

Thanks to @TomazicM I can now use:

let finalZoom = map.getView().getZoomForResolution(
  map.getView().getResolutionForExtent(
    ol.proj.transformExtent(
      ol.extent.boundingExtent(boundingBox),
      ol.proj.get('EPSG:4326'),
      ol.proj.get('EPSG:3857')
    ),
    map.getSize()
  )
);

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.