Harry
Harry

Reputation: 796

infowindow.close() does not act with multiple markers

I read a lot of solutions and tried several but in my script I can not getting it done.

I like to close the active infowindow when another marker is clicked.

Part of the code:

        for (var i = 0; i < locations.length; i++) {
          var centrum = locations[i];
          var myLatLng = new google.maps.LatLng(centrum[1], centrum[2]);
          var marker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              animation: google.maps.Animation.DROP,
              icon: image,
              shape: shape,
              title: centrum[0],
              zIndex: centrum[3]
          });
          marker['infowindow'] = new google.maps.InfoWindow({
              content: '<b>Informatie:</b><br>' + centrum[0]
          });
          google.maps.event.addListener(marker, 'click', function() {
              marker['infowindow'].close(); // has to close another active window
              this['infowindow'].open(map, this);
          });
        }

Someone a hint or better... a solution?

Thanks.

Upvotes: 1

Views: 2357

Answers (2)

Mauno V&#228;h&#228;
Mauno V&#228;h&#228;

Reputation: 9788

Keep only one reference to infowindow by storing it to variable like:

var infowindow = new google.maps.InfoWindow({content: "some text here..."});

thats the way to do it, now you are creating many intances of that class..

Check out full fiddle

Edit:

Infowindows with unique content fiddle

Upvotes: 1

Philippe Boissonneault
Philippe Boissonneault

Reputation: 3949

Keep markers in an array and add a call for a function to close all windows before opening the current one:

function closeInfos() {
    for(var i=0; i<markers.length; i++)
    {
        markers[i]['infowindow'].close();
    }
}

EDIT:

With your code, it should look something like that:

var markers = [];
for (var i = 0; i < locations.length; i++) {
          var centrum = locations[i];
          var myLatLng = new google.maps.LatLng(centrum[1], centrum[2]);
          var marker = new google.maps.Marker({
              position: myLatLng,
              map: map,
              animation: google.maps.Animation.DROP,
              icon: image,
              shape: shape,
              title: centrum[0],
              zIndex: centrum[3]
          }));
          marker['infowindow'] = new google.maps.InfoWindow({
              content: '<b>Informatie:</b><br>' + centrum[0]
          });
          markers.push(marker);
          google.maps.event.addListener(marker, 'click', function() {
              closeInfos();
              this['infowindow'].open(map, this);
          });
        }

Upvotes: 3

Related Questions