Google Maps API v3: Is there a callback or event listener for a setMap() event?

前端 未结 2 1989
猫巷女王i
猫巷女王i 2021-01-31 11:48

I am using Google Maps API v3 on a website I am developing. I have a drop-down box beneath my map which allows the user to switch between different sets of markers to be display

2条回答
  •  心在旅途
    2021-01-31 12:34

    There doesn't seem to be a callback or event listener for setMap(), but I figured out a way to accomplish what I wanted. I am loading the Google Map using jQuery. Here is my code.

    When initializing the map, I set up a listener for the 'idle' event, which hides the "loading" animation. The 'idle' event is triggered whenever the map is finished redrawing after a scroll or zoom change:

    google.maps.event.addListener(this.map, 'idle', function() {
     $('#loading').hide();
    });
    

    And in my function to clear overlays, I first show the loading animation, then clear each marker using setMap(null). Then I very slightly recenter the map by changing the longitude by .000000001. This happens after all the setMap() calls, and triggers the 'idle' event which hides the loading animation.

    // clear overlays from the map
    function clearOverlays() {
     $('#loading').show();
    
     // clear the markers from the active data array
     if (activeData) {
      for (i in activeData) { activeData[i].setMap(null); }
     }
     activeData = '';
    
     // very slightly recenter the map to trigger the 'idle' event
     var centerlat = MYMAP.map.getCenter().lat();
     var centerlng = MYMAP.map.getCenter().lng() + .000000001;
     recenter = new google.maps.LatLng(centerlat, centerlng);
     MYMAP.map.setCenter(recenter);
    }
    

    It is a bit of a hack, but I hope someone else finds this useful.

提交回复
热议问题