简体   繁体   中英

Error: There is no source with this ID in mapbox-gl-js

I want to remove source and layer from the map. Whenever i want to remove sources and layerrs form map then i am using removeSourceAndLayers() function.

const removeSourceAndLayers=(map)=>{
        for(var i=0;i<dataSet.length;i++){
            try{
                // source or layer might not pesent
                // which we are trying to remove
                if(map.getLayer(`empty-source-${i}`))
                    map.removeLayer(`empty-source-${i}`);
                if(map.getLayer(`complete-source-${i}`))
                    map.removeLayer(`complete-source-${i}`);
                if(map.getSource(`empty-source-${i}`))
                    map.removeSource(`empty-source-${i}`);
                if(map.getSource(`complete-source-${i}`));
                    map.removeSource(`complete-source-${i}`);
            }catch(e){
                console.log(e);
            }
        }
    }

I am getting this error.

DynamicRoute.jsx:39 Error: There is no source with this ID
    at i.removeSource (mapbox-gl.js:35)
    at r.removeSource (mapbox-gl.js:35)
    at removeSourceAndLayers (DynamicRoute.jsx:37)
    at clean (DynamicRoute.jsx:93)
    at commitHookEffectListUnmount (react-dom.development.js:19710)
    at commitPassiveHookEffects (react-dom.development.js:19768)

I am checking if source and layer present with the current id then remove otherwise continue.But, still error is appearing.

jsx:39 line is console.log(e); .

Your last if statement has a ; at the end, if you remove it, it will work.

if(map.getSource(`complete-source-${i}`)); // <---
    map.removeSource(`complete-source-${i}`);

The way your code is written now, it will have the same result as the code below, map.removeSource() is always called:

if(map.getSource(`complete-source-${i}`)) {
}

map.removeSource(`complete-source-${i}`);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM