How to Zoom and Center a Leaflet Map on a Single Marker
This article explains how to zoom and center a Leaflet JavaScript map on a single marker.
The Leaflet L.Map
class provides the fitBounds
method to zoom a map to contain a rectangular bounding box. The L.latLngBounds
utility function creates a bounding box object from an array of latitude and longitude coordinates. With a single marker, however, we only have one latitude and longitude coordinate from which to create the bounding box. The solution is to create a single-element array containing the latitude and longitude coordinate of the marker.
The following function centers and zooms a leaflet map on a single marker. Line 2 creates the single-element array containing the latitude and longitude coordinate of the marker. Line 3 creates the bounding box that encloses the marker’s location. Finally, line 4 zooms the map to enclose the bounding box.
1
2
3
4
5
function centerLeafletMapOnMarker(map, marker) {
var latLngs = [ marker.getLatLng() ];
var markerBounds = L.latLngBounds(latLngs);
map.fitBounds(markerBounds);
}
This code is available as a Gist.