Google Maps v3 adjust zoom level after map has been initialised

Jono picture Jono · Apr 18, 2011 · Viewed 29.6k times · Source

I am initialising a google map and periodicaly (every 30 seconds) updating markers/infowindows on the map. I am using Bounds to automatically zoom in but ensure that all markers/infowindows are visible.

My problem is that the infowindows are placed at the edge of the map and are often cut off. So, I need to zoom out by '1' each time the map is updated. I can use 'map.zoom' to determine the current zoom level and recalculate the new, desired value but I don't know how to set this new value.
Can the zoom parameter only be set upon intitialising the map?

Surely this is simple?

Below is my 'update' function;

function updatePage() {
//clear current markers
clearOverlays();

var location1 = new google.maps.LatLng(team1data.lat, team1data.lon);
var location2 = new google.maps.LatLng(team2data.lat, team2data.lon);
var bounds = new google.maps.LatLngBounds();
bounds.extend(location1);
bounds.extend(location2);
map.fitBounds(bounds);
var curZoom = map.zoom;
console.log(curZoom);
var newZoom = (curZoom - 1);
console.log(newZoom);



var infowindow1 = new google.maps.InfoWindow({
content: '<div style=\"height:100px;width:230px;font-size:12px;\"><span style="font-weight:bold;">' + team1data.user + ' (' + team1data.location + '): </span>' + team1data.tweet + '</div>'
});

var infowindow2 = new google.maps.InfoWindow({  
 content: '<div style=\"height:100px;width:230px;font-size:12px;\"><span style="font-weight:bold;">' +  team2data.user + ' (' + team2data.location + '): </span>' + team2data.tweet + '</div>'  
});  

//can add as many markers to the map as you like
var marker1 = new google.maps.Marker({
  position: location1,
  map: map,
  title: "Team 1"
});
markersArray.push(marker1);

google.maps.event.addListener(marker1, 'click',
function() {
  infowindow.open(map, marker);
});

var marker2 = new google.maps.Marker({
 position: location2, 
 map: map,
 title:"Team 2"
});
markersArray.push(marker2);

infowindow1.open(map, marker1);
infowindow2.open(map, marker2);

setTimeout("team1tweets()", 30000)
}

Answer

tomtastico picture tomtastico · Apr 18, 2011

According to the API reference, you can use map.setZoom(zoom)

https://developers.google.com/maps/documentation/javascript/reference/map#Map.setZoom

It is also better to use map.getZoom() to get the zoom level, as map.zoom will only tell you the initial zoom level, not the current one.