53

I'm trying to set the fitBounds option in a leaflet map like this:

var bounds = new L.LatLngBounds([[Math.max(lat, borneLat), Math.max(lng, borneLng)], [Math.min(lat, borneLat), Math.min(lng, borneLng)]]);
map.fitBounds(bounds, { padding: [20, 20] });

However this doesn't seem to add any padding ? at least the map "zoom level" doesn't change, and it's always showing the two points in the edges (i.e. one is top far right and the other is bottom far left). For some marker sets, it works ok, the zoom is at a decent level away and you can see everything nicely. However when the items are quite close to each other, it seems it zooms in a bit too much unless I can fit it with some "padding."

Also I'm unsure if the bounds would be correct like that? Should I use instead just:

var bounds = [[Math.max(lat, borneLat), Math.max(lng, borneLng)], [Math.min(lat, borneLat), Math.min(lng, borneLng)]];
João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
dan2k3k4
  • 1,388
  • 2
  • 23
  • 48

4 Answers4

76

map.fitBounds(bounds, {padding: []}) should work. I suggest you to change padding to eg. [50, 50], maybe your padding values are too small.

Check out this JSFiddle example.

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
yarl
  • 3,107
  • 1
  • 22
  • 28
  • On the JSFiddle, padding of [50, 50] works well, but still seems to show the same zoom level for me on my site, will try to increase it much higher (as it's happening when there's one point in the top right VS bottom left which are quite far away from each other). – dan2k3k4 Oct 17 '13 at 08:20
  • Hmm, seems I was running a much older version of leaflet so I updated that and it works fine now. Using [50, 50] for padding setting. Many thanks! – dan2k3k4 Oct 17 '13 at 08:47
9

I came across this problem. As I understand the padding is controlled by the zoom. In my example all padding settings under 10 make no difference. As soon as the padding goes to 10 the map is zoomed out one level and there is padding. Furhter increasing the padding value has no influence, until it is so big that another zoom-out level is reached.

T.G. Dallas
  • 113
  • 1
  • 6
9

Leaflet only zooms between integer-value zoom levels by default. Past version 1.0.0, "fractional zooms" are available with the "zoomSnap" parameter:

var map = L.map('map', {
    zoomSnap: 0.1
});

This will allow smaller padding values to be visible, but will also affect scrollWheelZoom behavior.

meetar
  • 7,443
  • 8
  • 42
  • 73
3

FWI, you can also set a max zoom level to the map like so:

var map = L.mapbox.map('map', 'mapbox.emerald', {
    maxZoom: 16
});

this way you can avoid the map zooming in too much in case the markers are too close togther.

Joe Black
  • 393
  • 1
  • 6
  • 10