TransWikia.com

.on("load") event for layer groups in Leaflet

Geographic Information Systems Asked by kykong on May 20, 2021

I have used Leaflet’s ImageOverlay to load various image layers onto a Leaflet map div (L.map). The size of the layer files can vary greatly. So some layers load very quickly while others can take a couple of seconds (and not every image layer file actually exists).

I would like to check whether all the layer files requested have been fully loaded before doing something else. I can find out if each individual layer is fully loaded using .on("load", function() { … }).

For example,

layer1 = L.imageOverlay(...);
layer2 = L.imageOverlay(...);
layer3 = L.imageOverlay(...);

layer1.on("load", function() {console.log("layer1 loaded")});
layer2.on("load", function() {console.log("layer2 loaded")});
layer3.on("load", function() {console.log("layer3 loaded")});

However, when I defined a LayerGroup,

var AllLayers = L.layerGroup([layer1, layer2, layer3]);

and then tried

AllLayers.on("load", function() {console.log("All layers loaded")});

I did not get "All layers loaded" in the console.

I came across a related question on the .on("click") event
.on(click) for layer groups in leaflet

I tried to define a layer group using L.featureGroup

var AllLayers = L.featureGroup([layer1, layer2, layer3]);

However, it did not show "All layers loaded" in the console either when all the layers were loaded.

I don’t know how I would go about trying the first method answered in the above article.

One Answer

A simple way of doing this would be to count load events of individual layers and when count is equal to number of layers, it's done.

Code could then look something like this:

var nLayers = 0;
var nLayersLoaded = 0;

function setLoadEvent(layer) {
  nLayers++;
  layer.on("load", function() {
    nLayersLoaded++;
    if (nLayersLoaded == nLayers) {
      console.log("all layers loaded");
    }
  });
}

setLoadEvent(layer1);
setLoadEvent(layer2);
setLoadEvent(layer3);

Correct answer by TomazicM on May 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP