views:

640

answers:

2

As the title states, on a given event (for me this happens to be upon opening a new google.maps.InfoWindow I want to be able to close any other currently open info windows. Right now, I can open many at a time..but I want only 1 open at a time.

I am creating the info windows dynamically (i.e. I don't know ahead of time how many will be generated), so in the click event of the current info window (which is where I want all the other open ones closed) I don't have a reference to any of the other open info windows on which to call close(). I am wondering how I can achieve this. I am not an experienced JavaScript programmer so I don't know if I need to use reflection or something similar here.

Would the best way be just to save all the references in some sort of collection, then loop through the list closing them all?

Thanks.

+4  A: 

I ran into the same problem and fixed it by creating a global info window.

var infowindow = new google.maps.InfoWindow();

Then I have a function to do the following on the click listener:

function getInfoWindowEvent(marker) {
    infowindow.close()
    infowindow.setContent("This is where my HTML content goes.");
    infowindow.open(map, marker);
}

This achieves what I think you're looking for b/c there is now only one info window on the map and I just close it, reload the content and open it again for the given marker.

jamesaharvey
A: 

It should be sufficient to have a global infowindow and then to change the position and content of that infowindow.

var infowindow = new google.maps.InfoWindow();

// Call this function to open an infowindow i.e. on click.
function respondToClick(latlng) {
  infowindow.setOptions({
    position: latlng,
    content" "Hello, world"
  });
}

As the same infowindow is used each time, you are guarantee'd to only ever have one open, and it uses less resources / memory than creating and then destroying multiple infowindows.

plexer