I am busy with a script that will make a google maps canvas on my website, with multiple markers. I want that when you click on a marker, a infowindow opens. I have done that, and the code is at the moment:
JavaScript
x
31
31
1
var latlng = new google.maps.LatLng(-34.397, 150.644);
2
var myOptions = {
3
zoom: 8,
4
center: latlng,
5
mapTypeId: google.maps.MapTypeId.ROADMAP
6
};
7
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
8
function addMarker(map, address, title) {
9
geocoder = new google.maps.Geocoder();
10
geocoder.geocode( { 'address': address}, function(results, status) {
11
if (status == google.maps.GeocoderStatus.OK) {
12
map.setCenter(results[0].geometry.location);
13
var marker = new google.maps.Marker({
14
position: results[0].geometry.location,
15
map: map,
16
title:title
17
});
18
google.maps.event.addListener(marker, 'click', function() {
19
var infowindow = new google.maps.InfoWindow();
20
infowindow.setContent('<strong>'+title + '</strong><br />' + address);
21
infowindow.open(map, marker);
22
23
});
24
} else {
25
alert("Geocode was not successful for the following reason: " + status);
26
}
27
});
28
}
29
addMarker(map, 'Address', 'Title');
30
addMarker(map, 'Address', 'Title');
31
This works 100%. But now i want that when one infowindow is open, and you want to open the second, the first one automaticly closes. But i haven’t found a way to do that. infowindow.close(); won’t help. Has someone an example or a solution to this problem?
Advertisement
Answer
infowindow is local variable and window is not available at time of close()
JavaScript
1
14
14
1
var latlng = new google.maps.LatLng(-34.397, 150.644);
2
var infowindow = null;
3
4
5
6
google.maps.event.addListener(marker, 'click', function() {
7
if (infowindow) {
8
infowindow.close();
9
}
10
infowindow = new google.maps.InfoWindow();
11
12
});
13
14