I am adding layers to my map dynamically based on whats available in the MapServer. I am looping over them so I can add them in the LayerControl. My issue is that I dont have access to the layers outside of the scope of the function which I need to run a map.hasLayer() function. What can I do to access the layers outside the fetch function to perform removeLayer and other things?
let url = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Infrastructure/MapServer";
let serviceUrl = url+'?f=pjson';
fetch(serviceUrl, {method:"get"})
.then(function(response) {
return response.json();
})
.then(function(esriService) {
esriService.layers.forEach(function(layer) {
let layerName = layer.name.replace(/\s/g, "");
let fullName = layer.name // return string
layerName = L.esri.dynamicMapLayer({
url: url,
layers: [layer.id]
}).addTo(map);
layerControl.addOverlay(layerName, fullName)
})
});
map.on('click', function (e) {
if (!map.hasLayer(mydefinedlayer)) {
console.log("Layer not displayed on map")
} else {
console.log("Layer displayed on map")
}
});