28

I have an overlay that is dynamically generated from user data, so I need to know how to find the center of that overlay.

Currently, I am just using the first coordinates from the overlay, but that really does not represent the center of the overlay. Therefore when I load the map, it is not centered on the overlay.

Does anyone have a good method for centering the map on the overlay, by calculating the center, not hard coding it?

var latlng = new google.maps.LatLng(38.269239, -122.276010);
    var myOptions = {
        zoom: 15,//Calculate this somehow?
        center: latlng,// Calculate value from array of coordinates?
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
Nic Hubbard
  • 41,587
  • 63
  • 251
  • 412

2 Answers2

93

If you have a list of coordinates, you can loop over them and add them to a LatLngBounds object. Here is a example for the V3 API, but the concept in V2 is similar:

var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coordinates.length; i++) {
  bounds.extend(coordinates[i]);
}

After that, you can get the center with:

bounds.getCenter();

Or alternatively, you can call map.fitBounds() directly, which will center the map around the center of the bounds and adjust the zoom, so that the whole bounds will fit exactly into the view port.

map.fitBounds(bounds);
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
tux21b
  • 90,183
  • 16
  • 117
  • 101
  • Could this same method be used to calculate the zoom? – Nic Hubbard Jul 23 '10 at 18:13
  • Just use any position and zoom level you want during the initialization and call `map.fitBounds(bounds);` afterwards as described. If you want to enforce some maximum zoom level, you will need to register a `zoomChangeBoundsListener` temporarily. Tell me if you need an example for that too. – tux21b Jul 23 '10 at 18:20
  • that worked alright in V2 of the api. in V3 the LatLngBounds must receive these 2 variables in this order: SW and NE, how do we know which is which? – Andres SK Sep 21 '11 at 01:22
15

Based on @tux21b,

      var bounds = new google.maps.LatLngBounds();
      polyline.getPath().forEach(function(e){//can't do polyline.getPath()[i] because it's a MVCArray
          bounds.extend(e);
      })         
      _map.fitBounds(bounds);
Anderson
  • 2,496
  • 1
  • 27
  • 41