infowindow closing and var (google maps api v3)
I have problem with closing infowindow when new is open in google maps api v.3.
var infowindow;
function addMarker(id, location) {
contentString = 'some content';
var marker = new google.maps.Marker({
position: location,
开发者_JS百科 map: map
});
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) infowindow.close();
infowindow.open(map, marker);
});
markersArray[id] = marker;
}
The problem is that in above code the old infowindow is not close when new one is clicked unless I delete var from the line var infowindow = new google.maps.InfoWindow({ But then all the infowindows have the same content...
Any help? Thanks.
Use a global variable to contain a pointer to the last opened marker, and when opening a new one, close the previous one. Like this
//var infowindow; // <-- removed; should not be global
var openedInfoWindow = null; // <-- added this here; make sure it's global
function addMarker(id, location) {
contentString = 'some content';
var marker = new google.maps.Marker({
position: location,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
google.maps.event.addListener(marker, 'click', function() {
if (openedInfoWindow != null) openedInfoWindow.close(); // <-- changed this
infowindow.open(map, marker);
// added next 4 lines
openedInfoWindow = infowindow;
google.maps.event.addListener(infowindow, 'closeclick', function() {
openedInfoWindow = null;
});
});
markersArray[id] = marker;
}
精彩评论