showing results for - "auto center map with multiple markers in google maps"
Kylian
10 Feb 2020
1//create empty LatLngBounds object
2var bounds = new google.maps.LatLngBounds();
3var infowindow = new google.maps.InfoWindow();    
4
5for (i = 0; i < locations.length; i++) {  
6  var marker = new google.maps.Marker({
7    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
8    map: map
9  });
10
11  //extend the bounds to include each marker's position
12  bounds.extend(marker.position);
13
14  google.maps.event.addListener(marker, 'click', (function(marker, i) {
15    return function() {
16      infowindow.setContent(locations[i][0]);
17      infowindow.open(map, marker);
18    }
19  })(marker, i));
20}
21
22//now fit the map to the newly inclusive bounds
23map.fitBounds(bounds);
24
25//(optional) restore the zoom level after the map is done scaling
26var listener = google.maps.event.addListener(map, "idle", function () {
27    map.setZoom(3);
28    google.maps.event.removeListener(listener);
29});