3

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

Just keep their names in an array in the window object, such as:

window.dynamicLayerNames = [];
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);
      window.dynamicLayerNames.push(layerName);
    })
  });
  • Thanks will have a go with that. Not sure if the hasLayer() function can take the layer itself or if it has to be the variable name of the layer – geogrow Feb 9 at 11:38
  • I think it did work, that you. That will move me forward – geogrow Feb 9 at 12:07
  • Method map.hasLayer() requires layer object. It worked because what you call layerName in your code is actually layer object. – TomazicM Feb 9 at 12:12

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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