Search code examples
leafletmarkerclusterer

Automatically Zoom the map to fit all markers


Following an example, you can see the plunker her http://plnkr.co/edit/lJHyP3dhT3v8aHVdt3D3?p=preview

Regardless of whatever zoom value is provided while initializitng the map, I want to zoom the map automatically so all the markers are inside the view. Here is my code

var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, Points &copy 2012 LINZ'
    }),
    latlng = L.latLng(-37.82, 175.24);

var map = L.map('map', {center: latlng, zoom: 10, layers: [tiles]});

var markers = L.markerClusterGroup();

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var title = a[2];
    var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
    marker.bindPopup(title);
    markers.addLayer(marker);
}

map.addLayer(markers);

var group = new L.featureGroup(markers);

map.fitBounds(group.getBounds());

Solution

  • You need to

    • create an array

    • push all your markers in array

    • once all the markers are added to array, create a featureGroup
    • add your markers array to featureGroup and then zoom to its bounds.

    Below is the modified code

    var markerArray = []; //create new markers array
    
    for (var i = 0; i < addressPoints.length; i++) {
        var a = addressPoints[i];
        var title = a[2];
        var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
        marker.bindPopup(title);
        markers.addLayer(marker);
    
        markerArray.push(marker); //add each markers to array
    
        if(i==addressPoints.length-1){//this is the case when all the markers would be added to array
            var group = L.featureGroup(markerArray); //add markers array to featureGroup
            map.fitBounds(group.getBounds());   
        }
    }
    

    Here is the working plunk