39

I have just copied the code on this question and applied my latitude and longitudes. However, the latitudes and longitudes will be dynamic, and the center of the map will change depending on the latitudes and longitudes of the locations.

The following is the code from the other question

<!DOCTYPE html>
<html>

    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>Google Maps Multiple Markers</title>
        <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    </head>

    <body>
        <div id="map" style="width: 500px; height: 400px;"></div>
        <script type="text/javascript">
            var locations = [
                ['Bondi Beach', -33.890542, 151.274856, 4],
                ['Coogee Beach', -33.923036, 151.259052, 5],
                ['Cronulla Beach', -34.028249, 151.157507, 3],
                ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
                ['Maroubra Beach', -33.950198, 151.259302, 1]
            ];

            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(-33.92, 151.25),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

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

            var marker, i;

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

                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(locations[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));
            }
        </script>
    </body>

</html>

So my question is, how could I know the center of the map when having dynamic locations. I've tried leaving the center blank but the map didn't load.

4 Answers 4

113

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

3
  • 3
    Add map.fitBounds(bound) to the code to fit the map zoom and center UI within bounds.
    – zookastos
    Commented Jun 22, 2017 at 20:48
  • a demo of the explained above - jsfiddle.net/3rhjwc5b/1 -- thanks @Salman!
    – jobwat
    Commented Jun 14, 2022 at 12:23
  • That works pretty well! Thanks for this!
    – Salman
    Commented Jun 14, 2022 at 19:46
3

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));
};
1
  • 1
    I'm using your logic with ruby and it's working, thank you
    – widjajayd
    Commented Jul 6, 2019 at 17:33
0

This approach does not work because it will average the numbers and not get the "middle" of the numbers (lat/long). Think of it like this, you have 6 points in the US, one in CA and 5 on east coast spread north and south. The 5 on east coast weight the average to the right(east) on the map and your center point would be (East to West) around Georgia. If you wanted to avoid using getCenter you would want to find the highest and the lowest of east direction (lat +/- and long +/-) and find the middle of each direction once you had the extremes.

0
private LatLng computeCentroid(List<LatLng> points) {
double latitude = 0;
double longitude = 0;
int n = points.size();

for (LatLng point : points) {
    latitude += point.latitude;
    longitude += point.longitude;
}

return new LatLng(latitude/n, longitude/n);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.