How do I clean up an InfoWindow when the associate

2019-02-25 21:07发布

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 Markervisibility 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?

2条回答
走好不送
2楼-- · 2019-02-25 21:30

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.

查看更多
3楼-- · 2019-02-25 21:35

For a single infoWindow I always create it as a global during map initialization. My click event starts with:

if(infoWindow != null){
   infoWindow.close();
}
infoWindow.setPosition(mouseEvent.latLng);
infoWindow.setContent("....");
// etc
查看更多
登录 后发表回答