Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
like image 646
coure2011 Avatar asked Sep 30 '15 08:09

coure2011


People also ask

How do you zoom all the way on a map?

Zoom in the mapDouble tap a spot on the map, and then: Drag down to zoom in. Drag up to zoom out.

How do I zoom in and embed in Google Maps?

Click on the chain-link "Share" icon, clicking back and forth between "Customize and preview embedded map" and your map itself until the result is to your liking, including zoom factor. Copy the resulting HTML code (iframe).


Video Answer


1 Answers

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

like image 59
muzaffar Avatar answered Oct 25 '22 03:10

muzaffar