I have the following code:
var locations = [
['Title 1', 41.33847249573162, 19.78838835516433],
['Title 2', 41.32992324524446, 19.816238906745866],
];
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 41.327546, lng: 19.818698}
});
setMarkers(map);
}
function setMarkers(map) {
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var locationInfowindow = new google.maps.InfoWindow({
content: 'Test content',
});
var marker = new google.maps.Marker({
position: {lat: location[1], lng: location[2]},
map: map,
title: location[0],
infowindow: locationInfowindow
});
google.maps.event.addListener(marker, 'click', function() {
this.infowindow.open(map, this);
});
}
}
When I click different markers, then different info windows open. How can I close all the info windows and open only the one corresponding to the marker I click?
put this code at first line
lastWindow=null;
then edit your click listener like this
google.maps.event.addListener(marker, 'click', function() {
if (lastWindow) lastWindow.close();
this.infowindow.open(map, this);
lastWindow=infowindow;
});
Another option is to only use a single Infowindow instead of creating an infowindow for each marker. Then whenever another marker is clicked on the infowindow simply moves to the new location with the new content. In this example the updated code would look like this:
var locationInfowindow = new google.maps.InfoWindow(); function setMarkers(map) { for (var i = 0; i < locations.length; i++) { var location = locations[i]; var marker = new google.maps.Marker({ position: {lat: location[1], lng: location[2]}, map: map, title: location[0] }); var content = 'Test Content: '+i; google.maps.event.addListener(marker,'click', (function(marker,content){ return function() { locationInfowindow.setContent(content); locationInfowindow.open(map,marker); }; })(marker,content)); } }