-1

In Google Maps v3, how do I close all currently open infowindows?

I can't just keep track of the last opened infowindow in a variable, as some have suggested, because in my setup each marker has unique text, and so I have to bind the infowindow to the marker at the point where it is created.

_.each(new_companies, function(c) {
  var latLng = new google.maps.LatLng(c.com_d_coo_y_wgs84,
      c.com_d_coo_x_wgs84);
  var marker = new google.maps.Marker({'position': latLng});
  marker.info = new google.maps.InfoWindow({
    content: getTooltipText(c)
  });
  google.maps.event.addListener(marker, 'mouseover', function() {
      marker.info.open(map, marker);
      // How to close all currently open info windows?
  });
  google.maps.event.addListener(marker, 'click', function() {
    marker.info.open(map, marker);
  });
  newco_markers.push(marker);
});

I guess I could loop through all the markers in newco_markers and close the infowindow for each, but that feels inefficient.

Community
  • 1
  • 1
Richard
  • 62,943
  • 126
  • 334
  • 542

1 Answers1

3

You should try using one infowindow and updating it's content and position via API methods: setPosition() and setContent()

Edit:

I made an assumption that you only needed one infowindow at a time. If you need more than one then you could try keeping a map(object) or array with references to the open info windows.

Rick
  • 1,563
  • 9
  • 11
  • This is the best solution - the only reason you should need more than one infowindow object is if you have to have multiple infowindows open at the same time – duncan Mar 07 '13 at 13:57
  • 1
    Unfortunately, I don't think that's going to work, because if I try to set the content with `infowindow.setContent(getTooltipText(c))` inside the loop, I end up with the same text bound to each marker. – Richard Mar 07 '13 at 15:04
  • 1
    Ah, figured it out - set the content as a property of `marker`, then `infowindow.setContent(marker.content)`. Thanks! – Richard Mar 07 '13 at 15:26
  • There are a few differing answers to this question on stack overflow. This is the correct one. It addresses the issue of why have multiple infowindows open in the first place. – Roffers Mar 29 '19 at 10:05