Skip to content Skip to sidebar Skip to footer

When To Use L.tilelayer Vs L.tilelayer

I have just been using Leaflet to build a map for a website and noticed that to add a Tile Layer at least two methods can be used, L.TileLayer() and L.tileLayer(), differing in the

Solution 1:

TL;DR:

These two are both valid and equivalent:

var foo = L.tileLayer(arguments);
var foo = new L.TileLayer(arguments);

These two are syntactically valid (because of Javascript's historical baggage) but will ultimately result in errors:

var foo = new L.tileLayer(arguments);
var foo = L.TileLayer(arguments);

to add a tilelayer at least two methods can be used, L.TileLayer() and L.tileLayer()

Well, they're not really two methods. Technically L.TileLayer is an instance of Object, and L.tileLayer is an instance of Function, which inherits the prototype of Object. And L acts as a namespace rather than a class instance.

You see, Object-Oriented Programming in Javascript is weird. You can use the new keyword with pretty much any object which has a prototype. And prototype-based inheritance is confusing to grasp to most people versed in "proper" OOP.

Nowadays, with the ES2015 standards and the fancy class keywords this is not really a problem (I'd say it's a problem, but hidden under layers of syntactic sugar). But back in the day, developers had to resort to, let's say, creative solutions for class inheritance which sometimes involves messing with the prototype chain.

Leaflet uses a combination of such methods - and as an undesired side effect, L.TileLayer becomes a Function and one can call L.TileLayer() directly and that's quite confusing.

Leaflet also uses the concept of factory functions: A function that returns an instance of a class. Quoting from one of the Leaflet tutorials:

Most Leaflet classes have a corresponding factory function. A factory function has the same name as the class, but in lowerCamelCase instead of UpperCamelCase:

functionmyBoxClass(name, options) {
    returnnewMyBoxClass(name, options);
}

This is meant just as a convenience: it saves the user from typing the new keyword back in an era where the new keyword was feared.

But this creates another undesired side effect, because in Javascript all Functions have a prototype, which means that you can do stuff like

function myFunction() { ... }
 var wtf = new myFunction();

Therefore, new L.tileLayer() is also valid syntax (but fails at runtime).


then what is the use of L.TileLayer()?

Once again, L.TileLayer() as a function call is an undesired side effect. But L.TileLayer represents a class and it's important to have a reference to that, because of things like:

if (layer instanceof L.TileLayer)

Post a Comment for "When To Use L.tilelayer Vs L.tilelayer"