Чтобы продлить данный ответ с несколькими полезными трюками:
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:
Дальнейших исследований в тему показывает, что fitBounds() является асинхронным и лучше всего сделать манипуляцию Zoom с прослушивателем, определенным перед вызовом Fit Bounds.
Спасибо @ Тим, @ xr280xr, больше примеров по теме: 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);
См http://stackoverflow.com/questions/2362337/how-to-set-the-google-map-zoom-level-to-show-all-the-markers – palmsey
вам нужно добавить 'latlng' в объект' bounds' каждый раз, когда вы добавляете маркер и устанавливаете карту в соответствии с окончательными границами. См. Ответ здесь: http://stackoverflow.com/questions/1556921/google-map-api-v3-set-bounds-and-center?rq=1 –