How does L.TileLayer load tiles, why doesn't it throw CORS errors?

2.3k views Asked by At

I am providing an URL which on executing gives me cors issue(Access denied)and if accessed via tilelayer function of leafletJs doesn't give me cors issue. Just wanted to understand how implementation of tileLayer is done.

I understand that cors issue(Access Denied) comes when origin is not whitelisted but in this case tileLayer also should give me access denied issue but instead it able to load the tiles in the map.

I referred below code to understand the implementation but could nt found how it is handling the cors issue differently. Any help is appreciated.
https://github.com/Leaflet/Leaflet/blob/master/src/layer/tile/TileLayer.js

1

There are 1 answers

0
IvanSanchez On

TL;DR: Leaflet only manipulates the DOM, and doing that never throws CORS errors.


Leaflet creates <img> DOM elements, and adds them to the DOM. The magic starts happening at this line of code:

var tile = document.createElement('img');

Then the src attribute is set, so that the element will look like <img src='foo/x/y/z.png'>:

tile.src = this.getTileUrl(coords);

Then, the functionality of L.GridLayer adds that <img> element to the DOM, over this line:

container.appendChild(tile);

Then there's a bit of magic to position that <img> inside some container elements so it stays in the right place, and resetting its CSS class when the image is loaded.

Leaflet manipulates the DOM. What Leaflet does not do is access the image information through javascript. In other words: Leaflet does not use XmlHttpRequest nor fetch.

Thus, the code will not throw errors related to CORS when loading resources, because that only happens when requesting resources through XmlHttpRequest or fetch.

You will, however, find CORS errors if you try to access the image data in your JS code (usually this is done through canvas functionality, see e.g. L.TileLayer.GL trying to use a loaded tile as a WebGL texture ). But in a basic scenario whis doesn't happen.

Also note that the image will fire an error event if it fails to load (due to HTTP error or otherwise). This, in turn, will make L.TileLayers fire a tileerror event. You might want to use an event handler for that if you're interested in looking at tile loading errors.