Find center of multiple locations in Google Maps

Solution 1:

First you can create a LatLngBounds object by including all the dynamically generated locations. Use the extend method to include the points. Then you can get the center of the bound using the getCenter method.

UPDATE:

Code:

var bound = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++) {
  bound.extend( new google.maps.LatLng(locations[i][2], locations[i][3]) );

  // OTHER CODE
}

console.log( bound.getCenter() );

Illustration:

enter image description here

Solution 2:

I'm doing this by averaging the latitudes and averaging the longitudes and using those averages as my center.

Example:

self.adjustPosition = function () {
    var lat = 0, lng = 0;

    if (self.nearbyPlaces().length == 0) {
        return false;
    }

    for (var i = 0; i < self.nearbyPlaces().length; i++) {
        lat += self.nearbyPlaces()[i].latitude;
        lng += self.nearbyPlaces()[i].longitude;
    }

    lat = lat / self.nearbyPlaces().length;
    lng = lng / self.nearbyPlaces().length;

    self.map.setCenter(new window.google.maps.LatLng(lat, lng));
};