[GIS] Calculating a bounding box by its center point and ratio, the map zoom and desired pixels width in Leaflet

coordinatesextentsleaflet

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?

EDIT

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).

Best Answer

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);