How to Zoom and Center a Leaflet Map on a Single Marker

This post explains how to zoom and center a Leaflet JS 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.

blog comments powered by Disqus