Google Maps API v3 infowindow close event/callback?

后端 未结 4 1009
攒了一身酷
攒了一身酷 2020-12-13 12:14

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

4条回答
  •  猫巷女王i
    2020-12-13 12:44

    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.

提交回复
热议问题