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?


Better way:

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

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

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:

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

if (map.getLayer("route")) {
| improve this answer | |

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

    try {
    catch(err) {
//        alert("Error!");
| improve this answer | |
  • 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.. – Fábio Dias Nov 11 '18 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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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