[GIS] Get all tileLayers from L.map object in Leaflet

leaflet

What is the best way to access all displayed tileLayers from a L.map object?

Traditionally, I have stashed tileLayers in an object that I can access later, like so:

var mapLayers = {}

if (! mapLayers[mapId]){
  mapLayers[mapId] = L.tileLayer(url);
}
map.addLayer(mapLayers[mapId]);

This works well enough, but I keep running into issues with it, and it seems like bad practice to store this data in an object I've created when it's already stored in the map object.

Internally, the map object stores tileLayers in map._layers, along with other layers (grids, feature layers…). They're indexed according to some internal leaflet scheme, so not sure if this is the best point of entry.

Using leaflet 0.7.3

Best Answer

Try the Map class's eachLayer() method:

var layers = [];
map.eachLayer(function(layer) {
    if( layer instanceof L.TileLayer )
        layers.push(layer);
});

For complex cases you would end up writing your own layer switcher, and I don't see anything wrong with that. The Leaflet library aims to provide a minimum of core functions for an interactive map. If you need a bigger, all-in-one solution, try OpenLayers.