How do I clean up an InfoWindow when the associated Marker is hidden?

╄→гoц情女王★ 提交于 2019-12-02 05:49:49

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10346001/how-do-i-clean-up-an-infowindow-when-the-associated-marker-is-hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!