[GIS] how to make a delay to wait for the map to load

ext-jsopenlayers-2

What code could I use to make it wait for the program to load the map first after the zoomIn command?

Here's a part of my code.

for (var z = zoomfrom; z <= zoomto; z++) { 
    var scale = MapPanel.map.getScale();
    var zoomlevel = MapPanel.map.getZoom();
    NewZoomLevel = getzoomlevel(scale); 
    lat1 = lat2tile(coords.top, NewZoomLevel);
    lat2 = lat2tile(coords.bottom, NewZoomLevel);

    long1 = long2tile(coords.left, NewZoomLevel);
    long2 = long2tile(coords.right, NewZoomLevel);

    for (var x= lat1; x<=lat2; x++) {
         for (var y= long1; y<=long2; y++) {
              list = list + startlink + zoomlevel + '/' + x + '/' + y + '<br>';
        } //y for
    } //x for
    MapPanel.map.zoomIn();

    // this part im hoping to put a code to wait for map to load after zoomIn                                                                                               
}; // z for

I tried using delayed function of extjs but to no avail.

Best Answer

Due to the asynchronous nature of JavaScript you can't "delay" code execution to wait for a certain event to happen, you need to use completion callbacks. OpenLayers.Map has a range of events you can listen to, the one you need is zoomend:

zoomend triggered after a zoom completes

Here's a simple example based on your code:

var map = MapPanel.map;
map.events.register('zoomend', map, function() {
  console.log('Zoom completed!');
});

console.log('About to zoom in');
map.zoomIn();
console.log('Zoom in started');

You can test it directly in your browser by pasting the code above (without the first line) into the JavaScript console on http://openlayers.org/. The output confirms that the execution order is what you'd expect:

About to zoom in

Zoom in started

Zoom completed!


However, it's not clear what you need the list variable for - depending on whether you'd like to use it before or after the zoom event you may need to rejiggle your code a bit.