How to automatically center a Google Maps instance with several markers using API v3?

I’m currently using this code to create a map with three markers:

function initMap() {
  var places = [
    ['PLACE 1', 41.926979, 12.517385],
    ['PLACE 2', 41.914873, 12.506486],
    ['PLACE 3', 41.918574, 12.507201]
  ];

  var myMap = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 15,
    center: new google.maps.LatLng(41.923, 12.513),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var infoWindow = new google.maps.InfoWindow();

  for (let j = 0; j < places.length; j++) {
    let position = new google.maps.LatLng(places[j][1], places[j][2]);
    let marker = new google.maps.Marker({
      position: position,
      map: myMap
    });

    google.maps.event.addListener(marker, 'click', (function(marker, j) {
      return function() {
        infoWindow.setContent(places[j][0]);
        infoWindow.open(myMap, marker);
      }
    })(marker, j));
  }
}

function loadGoogleMaps() {
  var script = document.createElement('script');
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initMap';
  document.body.appendChild(script);
}

window.onload = loadGoogleMaps;

My goal is to eliminate the need to manually set the map’s center using the coordinates center: new google.maps.LatLng(41.923, 12.513). Is there an automatic method to center the map based on the three marker locations?

You can use the LatLngBounds class from the Google Maps API to dynamically adjust the map’s center to fit all the markers. Here’s a quick approach: first, create a LatLngBounds object outside your loop. As you iterate over your markers, extend this bounds with each marker’s position. After adding all your markers, use myMap.fitBounds(bounds) to adjust the map’s center and zoom, like so:

var bounds = new google.maps.LatLngBounds();
for (let j = 0; j < places.length; j++) {
  let position = new google.maps.LatLng(places[j][1], places[j][2]);
  bounds.extend(position);
  let marker = new google.maps.Marker({
    position: position,
    map: myMap
  });
}
myMap.fitBounds(bounds);
``` This should center the map automatically based on your markers.

Another approach you might consider is recalculating the map center after adding all the markers by averaging the latitude and longitude of all your marker positions. Calculate an average latitude and longitude by summing these values for each of your markers and dividing by the number of markers. Once you have these average coordinates, set them as the center of the map. While this might not handle zoom automatically like using LatLngBounds, it can help if you prefer a simpler approach without relying on additional classes.