0

Please help, I have been suffering since 5 days. How can I get all layer Idsof a MapLibre map ?

function addLayer(map, options, layer) {
    let currentLayer = edges_data_api.find(
    element => element.edge_id === layer.feature.properties.edge_id)
    map.setPaintProperty('lines', 'fill-color', ['interpolate', ['linear'],
    ['get', currentLayer.lanes], 0, 'rgb(255, 255, 255)', 5, 'rgb(255, 0, 0)'])
    }

Here is how I defined the map with MapLibre

map.on('load', function() {
    map.addSource('lines', {
        type: 'geojson',
        data: data
    });

   map.addLayer({
        'id': 'lines',
        'type': 'fill',
        'source': 'lines',
        'layout': {},
        'paint': {
        'fill-color': '#4682B4',
        'fill-opacity': 0.8,
        }
    });
   map.setPaintProperty('lines', 'fill-color', ['get', 'color'])
})
aba2s
  • 452
  • 2
  • 18

3 Answers3

1

From Style Specification

A style's layers property lists all the layers available in that style.

So you can get map's layers from the style object using Map.getStyle()

map.getStyle().layers
gman
  • 116
  • 1
  • 4
0

As i know, there are no api for getAllLayers(). So u should keep list of layers' ids by you own.

//global variable
const layerIds = new Set()

map.on('load', function() {

    layerIds.add('lines') //keep list of ids without duplicates

    map.addSource('lines', {
        type: 'geojson',
        data: data
    });

   map.addLayer({
        'id': 'lines',
        'type': 'fill',
        'source': 'lines',
        'layout': {},
        'paint': {
        'fill-color': '#4682B4',
        'fill-opacity': 0.8,
        }
    });
   map.setPaintProperty('lines', 'fill-color', ['get', 'color'])
})


//You can iterate your list ids where it is needed
layerIds.forEach(value => {//action here})
SkaaRJ
  • 173
  • 1
  • 1
  • 14
  • lots of thanks. It's not working. I have nothing when I console.log(value) – aba2s Nov 30 '21 at 09:08
  • In this case, the `layerIds.forEach(value => {//action here})` would need to be called after the layers are added in the map `load` – abenrob Feb 28 '23 at 14:20
-1

This returns an array containing the ids of all layers:

Object.keys( map.style._layers )

But beware: the code accesses private fields both of Map and Style, therefore it may, however unlikely, no longer work for new versions of MapLibre.

Netzwolf
  • 1
  • 2