404

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

user2314737
  • 27,088
  • 20
  • 102
  • 114
Trikaldarshiii
  • 11,174
  • 16
  • 67
  • 95
  • 2
    See http://stackoverflow.com/questions/2362337/how-to-set-the-google-map-zoom-level-to-show-all-the-markers – palmsey Oct 10 '13 at 19:31
  • you need to add the `latlng` to a `bounds` object each time you add a marker and set your map to fit the final bounds. See the answer here: http://stackoverflow.com/questions/1556921/google-map-api-v3-set-bounds-and-center?rq=1 – Suvi Vignarajah Oct 10 '13 at 19:31

4 Answers4

753

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.

Bob van Luijt
  • 7,153
  • 12
  • 58
  • 101
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • 4
    From where did the `getPosition` method came from? – Pratheep Feb 14 '16 at 06:48
  • 6
    @Pratheep - it's part of the google.maps.Marker class; https://developers.google.com/maps/documentation/javascript/reference#Marker – Adam Jenkins Feb 14 '16 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 Apr 09 '18 at 02: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 Aug 14 '18 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](https://developers.google.com/maps/documentation/javascript/reference/map#Map.fitBounds) – MichaelM Sep 27 '18 at 12:37
  • map.fitBounds(bounds); solved everything!! Banging my head for the past 2 hours. Thanks – Ashwini Dec 08 '18 at 18:38
  • Any idea on how to achieve this in wordpress google maps? I am to display the markers but I'm looking for auto-zoom/fit-bounds? – Eswar Aug 24 '19 at 10:21
  • I found that calling `fitBounds()` after the loop where I add markers caused it to execute prematurely due to the process being asychronous. If this is the case for you, call `fitBounds()` on the final loop iteration. – alstr Aug 07 '20 at 12:48
202

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);
Community
  • 1
  • 1
d.raev
  • 9,216
  • 8
  • 58
  • 79
  • 4
    Good additions. Thanks! – paneer_tikka Apr 22 '15 at 06:34
  • 1
    I was having undefined returned by .getZoom(). [This answer](http://stackoverflow.com/a/13435411/263832) helped me solve it by using `addListenerOnce` on `zoom_changed` to set the zoom after its value has been initialized. – xr280xr Sep 18 '15 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. https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions – Tim Oct 09 '15 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. – Gustavo Straube Apr 28 '16 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 :)

iyogeshjoshi
  • 520
  • 1
  • 7
  • 15