Close all info windows google maps API V3?
As you see in the API docs, an InfoBox has a close()
-method.
Collect all the InfoBox'es you create in an array. Then iterate over this array and call close
for each infobox, when you need to close them all at once.
In the top, add an array to hold all the infoboxes created
jQuery(document).ready(function ($) {
var infoWindows = [];
In function showInContentWindow
add the following right after var infowindow=new..
, eg just before infowindow.open
//add infowindow to array
infoWindows.push(infowindow);
add this function
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}
here called by a link
<a href="#" onclick="closeAllInfoWindows();">Close all infowindows</a>
You can also keep your active (opened) info window in a higher scope or global variable
var activeInfoWindow;
and in the click event listener, close the active info window (if there's one), then set this
info window as active
var infoWindow = new google.maps.InfoWindow({
content: name
});
google.maps.event.addListener(marker, 'click', function() {
activeInfoWindow&&activeInfoWindow.close();
infoWindow.open(map, marker);
activeInfoWindow = infoWindow;
});
In case anyone wants to do this in the context of gmaps3 jQuery wrapper...
var infoWindows = [];
var locations=[
{position:[123,456],content:'<h3>marker title 1</h3><p>msg text</p>/div>'}
]
var map=$('#mapName').gmap3()
.marker(locations)
.infowindow(locations)
.then(function (infowindow) {
var map = this.get(0);
var marker = this.get(1);
marker.forEach(function(item,i){
item.addListener('click', function() {
closeAllInfoWindows();
infowindow[i].open(map, item);
infoWindows.push(infowindow[i]);
});
})
})
.fit();
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}