Skip to content
Advertisement

Leaflet createTile await for image to load

I am using the createTile with Vue2Leaflet library to make custom tiles. As far as I saw in the documentation, the function runs as many times as there are coords on the map. In my case, the function is triggered way more times than I have images to return so at the end I get 90%+ empty tiles that just clutter the map. I was wondering if there is a way to check whether or not an image has a valid path before it returns it? I tried using image.onload but it works after the function had already returned an empty tile.

    createTile: function (coords, done) {
      console.log(1);
      var src;
      src = `https://somecoolurl/${coords.x}_${coords.y}_${coords.z}.jpg`;
      const img = window.L.DomUtil.create("img");
      img.crossOrigin = "anonymous";
      img.src = src;
      img.onerror = function () {
        // handle on error
      };
      img.onload = function () {
        console.log(2);
        // handle if image src was valid
        done(null, img);
      };
      console.log(3);
      return img;
    }

In this case, the console will print 1 3 2.

If such thing is not possible and createTile has to always return a tile, is there a way I can remove tiles from the extended TileLayer once the tiles have been added to it?

Advertisement

Answer

The problem was that in my case I was generating multiple TileLayers and I was only specifying the tileSize and not the bounds. Therefore, the createTile was creating unnecessary empty tiles that lowered the performance of the map. It was when I also added bounds to each tile layer that the problem was resolved.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement