Sign in
Log inSign up

Google Maps API: Onclick on marker close infoWindow of other markers

Klevis Miho's photo
Klevis Miho
·May 30, 2016

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?