Search code examples
leafletfitbounds

Leaflet - Fitbounds and keep center


I'm using Leaflet with Mapbox and I'd like to set the view of the map so :

  1. all markers are visible
  2. the center is set to a specific point

It's easy to do each points separately with setView and fitbounds but I don't know how to have both at the same time since setView changes the bounds and fitBounds changes the center. A solution could be to define a center and a zoom but how can I know which zoom will allow all my markers to be visible ?

EDIT

I implemented the solution suggested by IvanSanchez and it works as expected:

let ne=leafletBounds.getNorthEast();
let sw=leafletBounds.getSouthWest();
let neSymetric=[ne.lat + (center.lat - ne.lat)*2, ne.lng + (center.lng - ne.lng)*2];
let swSymetric=[sw.lat +(center.lat - sw.lat)*2, sw.lng + (center.lng - sw.lng)*2];
leafletBounds.extend(L.latLngBounds(swSymetric, neSymetric));

Solution

  • Get your bounds, and create a second L.Bounds instance by applying point symmetry along the centerpoint you want. Create a new L.Bounds containing the original bounds and the symmetric bounds. Run fitBounds() with that.