API 4: Add all layers from a feature service to map

222
1
Jump to solution
06-22-2021 07:51 AM
LukasWürsch
New Contributor III

Hello there

I want to load all layers of a Hosted Feature service using the JS Api 4. It is possible to add a single layer to the map like this:

 

layer = new FeatureLayer({
      portalItem: {
        id: portalItemId
      }
      layerId: 0
    });

map.add(layer);

 

Is there a way to list, or count all layers within a Hosted Feature Service (using JS API 4), so each of them could be added using new FeatureLayer?

Or is there a direct way to add all layers of a Hosted Feature Service to the map?

Kind Regards

Lukas

 

0 Kudos
1 Solution

Accepted Solutions
LukasWürsch
New Contributor III

I figured out that this is possible to get the number of layers using the REST api and then add each layer individually. Please let me know in case there is a more direct way to achieve this.

// get number of layers in service
    let url = "...?f=pjson"; // Feature Service url from portal page
    esriRequest(url, {
      responseType: "json"
    }).then(function(response){
      let responseJSON = response.data;
      let numberOfLayers = responseJSON.layers.length;
      // load each service layer
      for (let i = 0; i < numberOfLayers; i++) {
        layer = new FeatureLayer({
          portalItem: {
            id: "..."
          },
          layerId: i
        });
        map.add(layer);
      }
    });

View solution in original post

1 Reply
LukasWürsch
New Contributor III

I figured out that this is possible to get the number of layers using the REST api and then add each layer individually. Please let me know in case there is a more direct way to achieve this.

// get number of layers in service
    let url = "...?f=pjson"; // Feature Service url from portal page
    esriRequest(url, {
      responseType: "json"
    }).then(function(response){
      let responseJSON = response.data;
      let numberOfLayers = responseJSON.layers.length;
      // load each service layer
      for (let i = 0; i < numberOfLayers; i++) {
        layer = new FeatureLayer({
          portalItem: {
            id: "..."
          },
          layerId: i
        });
        map.add(layer);
      }
    });

View solution in original post