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

        "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?

4 Answers 4


From: https://github.com/mapbox/mapbox-gl-js/issues/4466#issuecomment-288177042

To safely remove a layer that may or may not exist, guard the call to removeLayer with getLayer:

// Always remove the layer first to avoid an error
if (map.getLayer("route")) {

if (map.getSource("route")) {

Better way:

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

    if(typeof mapLayer !== 'undefined') {
      // Remove map layer & source.

I've solved in this manner, probably not the best solution but it's working

    try {
    catch(err) {
//        alert("Error!");
  • For the purpose on the title of the question (which describes perfectly what I was trying to do, albeit different of the question itself), this would not be a solution.. Commented Nov 11, 2018 at 17:12

Perhaps you could consider the following - It won't tell you if there's a previous layer or source, but it will update it to something new once it is moved. The MapboxGL API has different events to trigger .

Try this if you like:

Suppose the map was initially loaded, and then if the user moved or zoomed in on the map, you could use a


event. Here's an example:

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

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 } }); }

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

where data would be from an ajax call to your geojson source: ulrlz ='https:....jsonData.json'

type: 'GET',
 url: urlz ,
async: false,
dataType: 'json',
success: function (data) 
  map.getSource('route').setData(data); //SET THE DATA AGAIN FROM AJAX CALL
error: function (e) {

Once the call is made when you move or zoom, the source is updated and should redraw what you need.

If you like I could post a working example if you would want to follow this route.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.