pewpewlasers
pewpewlasers

Reputation: 3215

Centering Leaflet map with getbounds and related issues

I ran into a leaflet issue but I can't solve it. May be there's a easy solution I don't know.

So basically centering a map of grouped markers isn't so difficult and can be done like the following:

var markerLayer = L.featureGroup(marker)
        .addTo(map);

var bounds = markerLayer.getBounds();
map.fitBounds(bounds);

where marker is an array of markers. But my problem is that the marker array information I send to this code are generated by another system. So basically the marker can be far apart in the map or they can be really close.

When the markers are far apart the code above works perfectly and centers the map. However if the markers are really close (for example if they are from the same street), or better yet if there is only one marker problems arise. This is because getbounds will give me a rectangle that is so small that leaflet breaks (and this is of no use for the user as well). I mean the map basically tries to zoom in to that marker. So my question is how do I limit the zoom. For example if there is only marker in the map I want the map to show the marker and few streets around it.

Upvotes: 3

Views: 5184

Answers (2)

Daniel Gerber
Daniel Gerber

Reputation: 3470

The method map.fitBounds takes a parameter called maxZoom. This way you can have two maxZooms, one for the map and one for fitBounds.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You can give a maxZoom to the map and the fitBounds will not override it.

Upvotes: 2

Related Questions