Skip to content

Instantly share code, notes, and snippets.

@acdha
Created September 12, 2014 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdha/1218bcd9f2bb0818e6d7 to your computer and use it in GitHub Desktop.
Save acdha/1218bcd9f2bb0818e6d7 to your computer and use it in GitHub Desktop.
JS fragment to zoom a Leaflet JS map to fit all points
function fitBounds(map, initialBounds, fitOptions) {
var bounds = new L.LatLngBounds(),
options = {reset: true};
if (typeof(fitOptions) == 'undefined' && initialBounds && !initialBounds.getCenter) {
fitOptions = initialBounds;
initialBounds = null;
}
if (initialBounds) {
bounds.extend(initialBounds);
}
if (fitOptions) {
$.extend(options, fitOptions);
}
map.eachLayer(function (layer) {
if (layer.getLatLng) {
bounds.extend(layer.getLatLng());
}
});
if (bounds && bounds.isValid()) {
map.fitBounds(bounds, options);
} else {
map.fitWorld(options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment