Leaflet - Fitbounds and keep center
Asked Answered
S

2

7

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));
Slattern answered 27/6, 2016 at 9:52 Comment(0)
I
5

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.

Inquisition answered 27/6, 2016 at 10:33 Comment(1)
Thank you, that's an easy and efficient solution!Slattern
K
0

I found another solution to this. You can simply call map.panTo([lat, lng]) after you've adjusted your map with fitBound(). I am using VueJs and calling this in the mounted() lifecycle hook.

I am fitting bounds so you can see a user's location and also a geographic feature far away, but then I use panTo so the user's real location is at the center of the map after fitBounds. It seems to work seamlessly so far.

Krissykrista answered 18/8, 2017 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.