Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect progress loaded for GroundOverlay

I am loading 10 GroundOverlays onto a GoogleMap and would like to show the progress associated with loading the images.

var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(42.80059,-115.253806),
new google.maps.LatLng(47.481725,-110.227471));

var layer1 = new google.maps.GroundOverlay("overlays/layer1.png",imageBounds);
layer1.setOpacity(.5);
layer1.setMap(map);

How can I detect when the actual image of each overlay has loaded or the % loaded? I'd like to add a progress bar or something to show the user that overlays are loading as it can take 5 seconds or so.

like image 777
jotamon Avatar asked May 31 '12 12:05

jotamon


1 Answers

If you have one single image as a groundoverlay, I'd do the following:

  1. Create an img tag through javascript
  2. Set its src to overlays/layer1.png
  3. display a waiting box
  4. Add an onload event to it, on which load it as a gmaps overlay and close the waiting box.

Progress... that's a bit more browser specific. But loading is easy, so:

function loadOverlay(){
    var img = new Image();
    var img_url = "overlays/layer1.png"
    img.src= img_url;
    $('#wait_for_overlay').show();
    img.onLoad = function(){
        $('#wait_for_overlay').hide();
        var layer1 = new google.maps.GroundOverlay(img_url,imageBounds);
        layer1.setOpacity(.5);
        layer1.setMap(map);
    }
};

Reason why this will work:

Creating an img object and setting its 'src' attribute will make the browser start to download the requested file as soon as the javascript function doing this has finished.

The browser will put this image into its local cache, then call the onLoad function to see what should happen with it.

The callback actually does nothing to the img variable (perhaps it should, make sure it doesn't get wiped out as per closure rules, do a NOP with it if this is buggy), but instead calls the google-maps function.

The google-maps function will request the image at the exact same url, at which the browser will look up its cache table, and bring the image back immediately from cache.

This trick is nasty, but in fact, the google maps engine will do the exact same onLoad thingy in the background (as this is how map engines work).

I hope this satisfies your question... no progress bar, just a loading indicator... Perhaps you could do progress bar by requesting it with XHR and checking progress, I'm not sure, but the trick will be the same: do a faux request, in order to make it arrive to the cache.

like image 147
Aadaam Avatar answered Oct 21 '22 09:10

Aadaam