Mapbox No Source With This ID

4.7k views Asked by At

I want to remove sources and layers on Mapbox map. I managed to remove every sources and layers except for the first source and layer that I have added to Mapbox map.

Note that I am not good in using jQuery $.post.

Here is how I add all the sources and layers.

$.post('ajax/marker.php', function(data)
{
    var firstSplit = data.split(",");

    for(i=0;i<firstSplit.length-1;i++)
    {
        var secondSplit = firstSplit[i].split("|");
        var id = secondSplit[0];
        var lat = secondSplit[1];
        var lng = secondSplit[2];

        var point = {
            "type": "Point",
            "coordinates": [lat, lng]
        };

        map.addSource(id, { type: 'geojson', data: point });
        map.addLayer({
            "id": id,
            "type": "symbol",
            "source": id,
            "layout": {
                "icon-image": "airport-15"
            }
        }); 
    }
}); 

Remember that, I managed to view all the sources and layers on Mapbox map. Its just that I am not able to remove only the first source and layers that I have added to the map. I hope someone out there has some ideas regarding this problem. Thanks.

I used the two statements below in a loop to remove sources and layers.

map.removeSource(id);
map.removeLayer(id);

I did a test to remove the first source and layers manually as below but it did not work.

map.removeSource('1612280004A');
map.removeLayer('1612280004A');

However, it works on the next sources and layers.

3

There are 3 answers

0
Steve Bennett On

My best guess from what you've posted is that you can't remove the layer while there are still sources attached to it. Try reversing the order of your two statements:

map.removeLayer('1612280004A'); map.removeSource('1612280004A');

0
rajquest On

My GeoJson shared the same ID. Removing both layer and source fixed this issue

 function RemoveMapLayer() {
        var mpLayer = map.getLayer("points");
        if (typeof mpLayer === 'undefined') {
            // No Layer
        } else {
            map.removeLayer("points");
        }

        var mpSource = map.getSource("points");
        if (typeof mpSource === 'undefined') {
            alert("no source");
        } else {
            map.removeSource("points");
        }
    }

0
Vajiheh Habibi On

Before deleting, check if the source and layer are present, for example:

if (map.getLayer('points')){
    map.removeLayer('points');
}

if (map.getSource('point')){
    map.removeSource('point');
}