323

I've recently switched to Google Maps API V3. I'm working of a simple example which plots markers from an array, however I do not know how to center and zoom automatically with respect to the markers.

I've searched the net high and low, including Google's own documentation, but have not found a clear answer. I know I could simply take an average of the co-ordinates, but how would I set the zoom accordingly?

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),


    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

  setMarkers(map, beaches);
}


var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.423036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 121.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.450198, 151.259302, 1]
];

function setMarkers(map, locations) {

  var image = new google.maps.MarkerImage('images/beachflag.png',
      new google.maps.Size(20, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
    var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',

      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));


      var lat = map.getCenter().lat(); 
      var lng = map.getCenter().lng();      


  var shape = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

6 Answers 6

445

Yes, you can declare your new bounds object.

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

Then for each marker, extend your bounds object:

bounds.extend(myLatLng);
map.fitBounds(bounds);

API: google.maps.LatLngBounds

3
  • 51
    you may also add this map.setCenter(bounds.getCenter());
    – Raman Ghai
    Commented May 8, 2013 at 17:21
  • Both the answer and the comment by Raman helped whittle down my focus on what I needed.
    – JustJohn
    Commented May 1, 2016 at 17:15
  • Why fire map.fitBounds(bounds); every time a point is added, rather than just once at the end?
    – ashleedawg
    Commented Oct 9, 2021 at 11:42
199

Got everything sorted - see the last few lines for code - (bounds.extend(myLatLng); map.fitBounds(bounds);)

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(0, 0),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(
    document.getElementById("map_canvas"),
    myOptions);
  setMarkers(map, beaches);
}

var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 161.259052, 5],
  ['Cronulla Beach', -36.028249, 153.157507, 3],
  ['Manly Beach', -31.80010128657071, 151.38747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.159302, 1]
];

function setMarkers(map, locations) {
  var image = new google.maps.MarkerImage('images/beachflag.png',
    new google.maps.Size(20, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
    new google.maps.Size(37, 32),
    new google.maps.Point(0,0),
    new google.maps.Point(0, 32));
  var shape = {
    coord: [1, 1, 1, 20, 18, 20, 18 , 1],
    type: 'poly'
  };
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      shadow: shadow,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
    bounds.extend(myLatLng);
  }
  map.fitBounds(bounds);
}
6
  • 8
    Thanks! The 3.0 documents are surprisingly vague about where this functionality went.
    – Bill
    Commented Aug 30, 2010 at 15:06
  • 12
    The 3.0 documents are surprisingly vague about where a LOT of things went. :(
    – Scott
    Commented Nov 29, 2010 at 12:15
  • 5
    Sorry this is in the wrong place. It's meant to be a comment for the selected answer. But doesn't the extend function need to be inside your for loop?
    – kidbrax
    Commented Feb 12, 2011 at 14:04
  • 1
    Hello, great code but could this code be enhanced to avoid the "no images available at this zoom level". because this code doesn't take care of the zoom level, sure it does show all markers, but personnaly I'd prefer to see lower zoom to avoid the "no images ..." messages. Any idea please?
    – slah
    Commented Feb 12, 2011 at 14:04
  • Are these "bounds.extend(myLatLng); map.fitBounds(bounds);" available for Android as well?
    – lionfly
    Commented Jul 22, 2011 at 9:06
7

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));
5

My suggestion for google maps api v3 would be(don't think it can be done more effeciently):

gmap : {
    fitBounds: function(bounds, mapId)
    {
        //incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
        if (bounds==null) return false;
        maps[mapId].fitBounds(bounds);
    }
}

In the result u will fit all points in bounds in your map window.

Example works perfectly and u freely can check it here www.zemelapis.lt

2
  • Instead of returning false if the bounds are null, you could maps[ mapId ].getBounds().
    – kaiser
    Commented Nov 18, 2013 at 10:16
  • @localtime actually, your web site needs Google Maps API keys to work
    – user3638471
    Commented Nov 16, 2016 at 11:34
-1

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

-15

Use below one,

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

2
  • 14
    This is for Google Maps API v2
    – dave1010
    Commented Apr 30, 2010 at 8:59
  • You need to provide a more thought out solution. And I believe this is for Google Maps v2.
    – AllJs
    Commented Feb 16, 2017 at 20:54

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