409

I am setting multiple markers on my map and I can set statically the zoom levels and the center but what I want is, to cover all the markers and zoom as much as possible having all markets visible

Available methods are following

setZoom(zoom:number)

and

setCenter(latlng:LatLng)

Neither setCenter supports multiple location or Location array input nor setZoom does have this type of functionality

enter image description here

2

4 Answers 4

760

You need to use the fitBounds() method.

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

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

8
  • 4
    From where did the getPosition method came from?
    – Pratheep
    Commented Feb 14, 2016 at 6:48
  • 6
    @Pratheep - it's part of the google.maps.Marker class; developers.google.com/maps/documentation/javascript/… Commented Feb 14, 2016 at 12:51
  • 13
    Just as an aside for the newbies out there, with the same question as Pratheep... You know this if you're experienced with the Maps API, but you can always pass in a LatLngLiteral instead of having a Marker instance. e.g., bounds.extend({lat: 123, lng: 456}).
    – Kyle Baker
    Commented Apr 9, 2018 at 2:23
  • For some reason when I iterate through an array of markers, getPosition always returns undefined. I fixed this by calling bounds.extend every time I create a marker.
    – Don't Know
    Commented Aug 14, 2018 at 17:23
  • 3
    An extra tip for anyone interested. You can define a padding by using fitBounds(bounds, int) which will allow you to have a little space between the markers and the map edges (or less space if you need). See Documentation
    – MichaelM
    Commented Sep 27, 2018 at 12:37
203

To extend the given answer with few useful tricks:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

UPDATE:
Further research in the topic show that fitBounds() is a asynchronic and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);
3
  • 1
    I was having undefined returned by .getZoom(). This answer helped me solve it by using addListenerOnce on zoom_changed to set the zoom after its value has been initialized.
    – xr280xr
    Commented Sep 18, 2015 at 18:43
  • 1
    Thanks @d.raev but setting the max zoom when boundaries are already set doesn't work. What you must do is set the "maxZoom" option when initializing your map. developers.google.com/maps/documentation/javascript/…
    – Tim
    Commented Oct 9, 2015 at 14:33
  • 1
    In the part about the zoom manipulation (UPDATE), you're mixing a couple vars and scopes. You use yourMap, map and this. Maybe it's a good idea to make it more consistent. Commented Apr 28, 2016 at 12:44
14

The size of array must be greater than zero. Οtherwise you will have unexpected results.

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}
8

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

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