Automatically scale the map to fit all markers

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

No matter what scaling value is provided when initializing the map, I want to automatically scale the map so that 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()); 
+7
leaflet markerclusterer
source share
1 answer

You need

  • create an array

  • click all markers in the array

  • Once all tokens are added to the array, create a featureGroup
  • add an array of markers to featureGroup and then increase its borders.

Below 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 a working plunk

+10
source share

All Articles