In addition to the map, we declare a global array variable, infowindows. Accessing this variable allows us to close all InfoWindows.
When initializing the map, we add a click listener so we can place markers.
function initialize() {
map = new google.maps.Map($("map_canvas"), mapOptions);
google.maps.event.addListener(map, 'click', function (event) {
addMarker(event.latLng, "InfoWindow index #" + infowindows.length);
});
}
When adding markers, we also add the InfoWindow and its contents at the same time.
function addMarker(pos, content) {
var marker = new google.maps.Marker({
map: map,
position: pos
});
var infowindow = new google.maps.InfoWindow({
content: content
});
infowindows.push(infowindow);
google.maps.event.addListener(marker, 'click', function (event) {
closeInfoWindows();
infowindow.open(map, marker);
});
}
Finally, we define a simple function that closes all InfoWindows. Without an array to keep track of them, we cannot locate the previously opened InfoWindow(s).
function closeInfoWindows() {
for (var i = 0; i < infowindows.length; i++) {
infowindows[i].close();
}
}
Full source code:
No comments:
Post a Comment