I'm trying to add dynamically an overlay on a leaflet map.

I know the

  • overlay center - {lat:50.8466,lng:4.3528}
  • overlay ratio - 16/9
  • map zoom - 15
  • desired pixels width - 200px

How can I calculate a bounding box based on those parameters?


I ended up working with the map size (in pixels) rather that with the map zoom; with the method containerPointToLatLng():

Given a pixel coordinate relative to the map container, returns the corresponding geographical coordinate (for the current zoom level).

  • 1
    I wonder if this would be simpler with just a L.Marker for the 200px-wide-image. – IvanSanchez Feb 14 '20 at 20:45

You can use map's project method to get map pixel coordinate for the current map CRS at desired zoom. Then calculate diagonal bounding box points by offsetting projected overlay center coordinate, unproject those point back to lat,lng coordinates with map's unproject method and get bounding box with L.latLngBounds method.

Code could then look something like this:

var overlayCenter = L.latLng([50.8466, 4.3528]);
var mapZoom = 15;
var pixWidth = 200;
var pixOffsetX = pixWidth / 2;
var pixOffsetY = pixOffsetX * 9 / 16;

var centerPoint = map.project(overlayCenter, mapZoom);
var latLng1 = map.unproject(L.point([centerPoint.x - pixOffsetX, centerPoint.y + pixOffsetY]), mapZoom);
var latLng2 = map.unproject(L.point([centerPoint.x + pixOffsetX, centerPoint.y - pixOffsetY]), mapZoom);
var bbox = L.latLngBounds(latLng1, latLng2);

We these information, it is not possible.

First you need a projection system to convert your geodetic coordinate system to a planar coordinate system. You don’t have that CRS.

Secondly, you would need to know the exact scale. Zoom level is not enough here, as it shows an spectrom not an exact scale.

If you are able to find the above deficiencies you would be able to calculate your bounding box.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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