简体   繁体   中英

Leaflet.js fitBounds with padding?

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 (ie 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)]];

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 .

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM