[GIS] How to toggle ArcGIS webmap layers using ArcGIS Javascript API

arcgis-javascript-apiarcgis-online

I've created a webmap using ArcGIS Online that I want to render in a web app using the ArcGIS for Javascript API. In ArcGIS Online, I've saved the webmap with all of the layers off (visibility: false). I want set the visibility of one layer ("Layer X" below) to true using the API.

    arcgisUtils.createMap(mapid, "map").then(function(response){

         layers = response.itemInfo.itemData.operationalLayers;

         dojo.forEach(layers, function(layer){

             if (layer.title == 'Layer X') {
                 layer.setVisibility(true)**;
             }
             console.log(layer.title + ", visibility: " + layer.visibility);

         });

     });

**I've tried using .show() as well.

Using the code snippet above, the visibility of "Layer X" doesn't change. The console log reports the layer title & visibility of all the layers except the one I'm trying to show.

The response object returned from the .createMap method is a Deferred object.

Is it possible to toggle the layers of a webmap using the ArcGIS for Javascript API, or is the response object immutable?

Best Answer

The layer object returned via the createMap response doesn't have the property "setVisibility."

However, it does has a property called "layerObject," which seems to be the actual map object. The code snippet below does the trick:

 layer.layerObject.setVisibility(true)
Related Question