[GIS] How to test if a layer exist in a MapBox GL JS map

javascriptmapboxmapbox-glmapbox-gl-js

I load a GeoJSON layer in a MapBox GL JS map in this way ….

    map.addSource("route", {
        "type": "geojson",
        "data": {
            "type": "Feature",
            "properties": {},
            "geometry": theCoords
        }
    });

    map.addLayer({
        "id": "route",
        "type": "line",
        "source": "route",
        "layout": {
            "line-join": "round",
            "line-cap": "round"
        },
        "paint": {
            "line-color": "#ff0000",
            "line-width": 4
        }
    });  }

… but I need to check if the "route" source and layer exist in my map to remove them before to load the new layer with the same source and name

Does exist in MapBox GL JS any way to test if "route" source and layer exist in my map?

Suggestions / examples / useful links?

Best Answer

Better way:

var mapLayer = map.getLayer('route');

    if(typeof mapLayer !== 'undefined') {
      // Remove map layer & source.
      map.removeLayer('route').removeSource('route');
    }
Related Question