How can I check whether Google Maps is fully loaded?

后端 未结 9 1178
野性不改
野性不改 2020-11-22 13:44

I’m embedding Google Maps into my web site. Once Google Maps is loaded, I need to kick off a few JavaScript processes.

Is there a way to auto-detect when Goo

相关标签:
9条回答
  • 2020-11-22 14:20

    Where the variable map is an object of type GMap2:

        GEvent.addListener(map, "tilesloaded", function() {
          console.log("Map is fully loaded");
        });
    
    0 讨论(0)
  • 2020-11-22 14:25

    In 2018:

    var map = new google.maps.Map(...)
    map.addListener('tilesloaded', function () { ... })
    

    https://developers.google.com/maps/documentation/javascript/events

    0 讨论(0)
  • 2020-11-22 14:32

    If you're using web components, then they have this as an example:

    map.addEventListener('google-map-ready', function(e) {
       alert('Map loaded!');
    });
    
    0 讨论(0)
  • 2020-11-22 14:32

    In my case, Tile Image loaded from remote url and tilesloaded event was triggered before render the image.

    I solved with following dirty way.

    var tileCount = 0;
    var options = {
        getTileUrl: function(coord, zoom) {
            tileCount++;
            return "http://posnic.com/tiles/?param"+coord;
        },
        tileSize: new google.maps.Size(256, 256),
        opacity: 0.5,
        isPng: true
    };
    var MT = new google.maps.ImageMapType(options);
    map.overlayMapTypes.setAt(0, MT);
    google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
        var checkExist = setInterval(function() {
            if ($('#map_canvas > div > div > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > div > div').length === tileCount) {
                callyourmethod();
                clearInterval(checkExist);
            }
        }, 100); // check every 100ms
    });
    
    0 讨论(0)
  • 2020-11-22 14:33

    You could check the GMap2.isLoaded() method every n milliseconds to see if the map and all its tiles were loaded (window.setTimeout() or window.setInterval() are your friends).

    While this won't give you the exact event of the load completion, it should be good enough to trigger your Javascript.

    0 讨论(0)
  • 2020-11-22 14:35

    This was bothering me for a while with GMaps v3.

    I found a way to do it like this:

    google.maps.event.addListenerOnce(map, 'idle', function(){
        // do something only the first time the map is loaded
    });
    

    The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce method the code in the closure is executed the first time "idle" is fired and then the event is detached.

    See also the events section in the Google Maps Reference.

    0 讨论(0)
提交回复
热议问题