[GIS] OpenLayers: adding a loading indicator for WMS requests

loadingopenlayers-2wms

I'm new to Openlayers and GIS in general. I have a WMS request followed by the addLayer method, and surrounded by the addition and deletion of a 'loading' class to an HTML element:

$(toggle).parent('div').first().addClass('loading');
Map.currentOverlay = new OpenLayers.Layer.WMS(name, Constants.webServices.wms, {
    format: 'image/png',
    tiled: false,
    transparent:true
  }, {
    singleTile:true,
    ratio:1,
    getURL: Projection.getDefaultOverlayUrl 
  });
}
if (Map.currentOverlay != null) {
  Map.currentOverlay.initialZoom = map.zoom;
  Map.currentOverlay.isBaseLayer = false;
  Map.currentOverlay.visibility = true;
  Map.currentOverlay.events.on({moveend: Map.__onZoomUpdate});
  map.addLayer(Map.currentOverlay);
  $(toggle).parent('div').first().removeClass('loading');

My goal is to add a loading gif in a dialog window (with CSS) while the layer is not displayed yet. According to this post: https://stackoverflow.com/questions/9569847/when-does-openlayers-wms-physically-call-the-remote-server the request is done in the addLayer method. But it seems asynchronous: the class 'loading' is added and removed straight away, while the map is not yet displayed.
Can I add a callback or something similar to addLayer ? If not, how do I do?

NB: I didn't produce the above code, I just added the "loading" behaviour. Do not hesitate to tell me if something seems wrong with it.

Best Answer

You can use the loadstart and loadend events on the layer to handle this. This example (http://openlayers.org/dev/tests/manual/loadend.html) shows the basics of how to get it working.