It would seem there's no "out of the box" way to know when an ImageMapType overlay has finished loading, but thanks to a suggestion from Martin over on the Google Maps API v3 Forums I was able to add in my own custom event that is emitted when the layer finishes loading.
The basic approach is:
- Every time a URL is requested, add the URL to a list of pending URLs
- Override ImageMapType.getTile() so that we can add "onload" event listeners to each <img> element.
- When each image's "load" event fires, remove that image from the list of pending URLs.
- When the list of pending URLs is empty, then emit our custom "overlay-idle" event.
I've copied the code below for posterity, but you can see it in action on jsFiddle: http://jsfiddle.net/6yvcB/22/
// Create a base map
var options = {
zoom: 3,
center: new google.maps.LatLng(37.59, -99.13),
mapTypeId: "terrain"
};
var map = new google.maps.Map($("#map")[0], options);
// Listen for the map to emit "idle" events
google.maps.event.addListener(map, "idle", function(){
console.log("map is idle");
});
// Keep track of pending tile requests
var pendingUrls = [];
$("#btn").click(function() {
var index = 0;
var urls = [ "http://placekitten.com/256/256",
"http://placekitten.com/g/256/256",
"http://placekitten.com/255/255",
"http://placekitten.com/g/255/255",
"http://placekitten.com/257/257",
"http://placekitten.com/g/257/257" ];
var overlay = new google.maps.ImageMapType({
getTileUrl: function() {
var url = urls[index % urls.length];
index++;
// Add this url to our list of pending urls
pendingUrls.push(url);
// if this is our first pending tile, signal that we just became busy
if (pendingUrls.length === 1) {
$(overlay).trigger("overlay-busy");
}
return url;
},
tileSize: new google.maps.Size(256, 256),
isPng: true,
opacity: 0.60
});
// Listen for our custom events
$(overlay).bind("overlay-idle", function() {
console.log("overlay is idle");
});
$(overlay).bind("overlay-busy", function() {
console.log("overlay is busy");
});
// Copy the original getTile function so we can override it,
// but still make use of the original function
overlay.baseGetTile = overlay.getTile;
// Override getTile so we may add event listeners to know when the images load
overlay.getTile = function(tileCoord, zoom, ownerDocument) {
// Get the DOM node generated by the out-of-the-box ImageMapType
var node = overlay.baseGetTile(tileCoord, zoom, ownerDocument);
// Listen for any images within the node to finish loading
$("img", node).one("load", function() {
// Remove the image from our list of pending urls
var index = $.inArray(this.__src__, pendingUrls);
pendingUrls.splice(index, 1);
// If the pending url list is empty, emit an event to
// indicate that the tiles are finished loading
if (pendingUrls.length === 0) {
$(overlay).trigger("overlay-idle");
}
});
return node;
};
map.overlayMapTypes.push(overlay);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…