Google Maps API v3 infowindow close event/callback?

Viewed 72507

I like to keep track of any and all infowindows that are open on my Google Maps interface (I store their names in an array), but I can't figure out how to remove them from my array when they are closed via the "x" in the upper right hand corner of each one.

Is there some sort of callback I can listen for? Or maybe I can do something like addListener("close", infowindow1, etc ?

6 Answers
infoWindow.addListener('closeclick', ()=>{
  // Handle focus manually.
});

Simplifying and extending the most upvoted solution, you can create the marker during the handling of the marker click event, letting you package its removal due to the x icon's closeclick event at the same time.

Here's an example that includes duplicate info window creation avoidance by tacking a boolean hasInfoWindow status on markers.

  newMarker.addListener('click', function () {
    // If a marker does not yet have an info window, create and show it
    if (newMarker['hasInfoWindow'] !== true) {
      newInfoWindow = new google.maps.InfoWindow({content: infoContent}); 
      mapSet['infoWindowsObj'].push(newInfoWindow);
      newMarker['hasInfoWindow'] = true;
      newInfoWindow.open(mapSet, newMarker);

      // If info window is dismissed individually, fully remove object
      google.maps.event.addListener(newInfoWindow, 'closeclick', function () {
        newInfoWindow.setMap(null);
        newMarker['hasInfoWindow'] = false;
        mapSet['infoWindowsObj'].filter(arrayItem => arrayItem !== newInfoWindow);
      });
    }
  });

Then if you want to remove all open info windows due to a click event on a map, you can iterate through the contents of mapSet['infoWindowsObj'] to fully remove each.

I believe this behavior lets you get away with using infowindow for most cases without having to reimplement the whole thing as per google's custom popup example.

this is very simple find the class of close infowindow button, that is '.gm-ui-hover-effect'

trigger to close infowindow

$('.gm-ui-hover-effect').trigger('click');

Related