Close all info windows google maps API V3?

前端 未结 3 1096
[愿得一人]
[愿得一人] 2020-12-14 20:20

How do i get all info windows to close upon clikcing another pin or clicking the map in itself? I\'m using http://google-maps-utility-library-v3.googlecode.com/svn/trunk/in

相关标签:
3条回答
  • 2020-12-14 20:32

    In case anyone wants to do this in the context of gmaps3 jQuery wrapper...

    var infoWindows = [];
    var locations=[
        {position:[123,456],content:'<h3>marker title 1</h3><p>msg text</p>/div>'}
    ]
    var map=$('#mapName').gmap3()
    .marker(locations)
    .infowindow(locations)
    .then(function (infowindow) {
        var map = this.get(0);
        var marker = this.get(1);
        marker.forEach(function(item,i){
            item.addListener('click', function() {
                closeAllInfoWindows();
                infowindow[i].open(map, item);
                infoWindows.push(infowindow[i]);
            });
        })
    })
    .fit();
    
    function closeAllInfoWindows() {
      for (var i=0;i<infoWindows.length;i++) {
         infoWindows[i].close();
      }
    }
    
    0 讨论(0)
  • 2020-12-14 20:34

    As you see in the API docs, an InfoBox has a close()-method.

    Collect all the InfoBox'es you create in an array. Then iterate over this array and call close for each infobox, when you need to close them all at once.

    In the top, add an array to hold all the infoboxes created

    jQuery(document).ready(function ($) {
        var infoWindows = [];
    

    In function showInContentWindow add the following right after var infowindow=new.., eg just before infowindow.open

    //add infowindow to array
    infoWindows.push(infowindow); 
    

    add this function

    function closeAllInfoWindows() {
      for (var i=0;i<infoWindows.length;i++) {
         infoWindows[i].close();
      }
    }
    

    here called by a link

    <a href="#" onclick="closeAllInfoWindows();">Close all infowindows</a>
    
    0 讨论(0)
  • 2020-12-14 20:45

    You can also keep your active (opened) info window in a higher scope or global variable

    var activeInfoWindow;
    

    and in the click event listener, close the active info window (if there's one), then set this info window as active

    var infoWindow = new google.maps.InfoWindow({
      content: name
    });
    
    google.maps.event.addListener(marker, 'click', function() {
      activeInfoWindow&&activeInfoWindow.close();
      infoWindow.open(map, marker);
      activeInfoWindow = infoWindow;
    });
    
    0 讨论(0)
提交回复
热议问题