I know that many of us are writing code to open an InfoWindow
when a marker is clicked. But the InfoWindow
will stay in place until the upper-right X is clicked, which means that setting the associated Marker
visibility to false
will create what is essentially an orphaned InfoWindow
. And there could be multiple InfoWindow
instances displayed on the Map at the same time. I guess it's simple enough for the user to just click the InfoWindow
closed, but it feels like hiding the Marker
should hide the associated InfoWindow
.
I have started writing code like the following to deal with this scenario:
google.maps.event.addListener( marker, "click", function() {
var bubble = new google.maps.InfoWindow({
content: buildBubbleContent( param1, param2 )
});
bubble.open( map, marker );
//pretty standard stuff to here, but the next line is new (for me):
google.maps.event.addListenerOnce( marker, "visible_changed", function() {
bubble.close();
});
});
Is this what everyone else is doing? It feels like a design pattern that should be called a ListenBack. I've never seen the issue addressed in the Google Maps docs. I can't help but think that there must be a simpler mechanism built into the InfoWindow
to take care of this automatically. Is there a standard way to do this that I have just missed?
I'm marking this question as answered, because I have continued scouring the docs and looking at many code samples, but haven't found any other solutions. There is certainly no facility provided with the InfoWindow to automatically remove it from the map when the associated marker is turned off. If anyone finds a better option later, I will happily mark their solution as the better answer.
For a single infoWindow I always create it as a global during map initialization. My click event starts with: