Google Maps v3 adjust zoom level after map has been initialised
Asked Answered
T

1

11

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)
}
Thermolysis answered 18/4, 2011 at 9:43 Comment(0)
A
25

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.

Antibes answered 18/4, 2011 at 9:52 Comment(1)
In some cases setZoom(..) does not work if called immediately after some operation. Another answer describes how to use the "idle" event to perform the operation when map is ready to accept commands: #2438183Schreibe

© 2022 - 2024 — McMap. All rights reserved.