webmap_item = gis.content.get(webmap_id)
view_item = gis.content.get(view_id)
# interrogate webmap_item to get a specific lyr to remove
wm = WebMap(webmap_item)
wm.remove_layer(lyr)
wm.update() # success
wm.add_layer(view_item)
wm.update() # partial success, partial fail
# item is added but as individual layers in reverse order
The result of line 7 is that each layer contained in the view gets added to the WebMap individually in reverse order, not as a single GroupLayer.
I would like to add the hosted feature layer view as a single GroupLayer to the WebMap.
TIA
Solved! Go to Solution.
Python API 2.4.0 now supports Group Layers
Edits to your code for this to work in 2.4.0:
webmap_item = gis.content.get(webmap_id)
view_item = gis.content.get(view_id)
wm = Map(item=webmap_item)
wm.content.remove(0) #index of layer to remove
wm.update()
wm.content.add(view_item)
wm.update()
Hi @Dirk_Vandervoort.,
Check out the below. I would urge you to make a copy of your WebMap and test before running! Code is commented and taken from multiple blog posts available here.
The below adds the layers in reverse order (which is the order you want) and then groups those layers added in the WebMap. Currently no neat function for this but I believe it is on the way. Workaround available here.
from arcgis.gis import GIS
from arcgis.mapping import WebMap
## access ArcGIS Online
agol = GIS("home")
## get the Feature Service as an Item object
view_item = agol.content.get("VIEW_ITEM_ID")
## the wm item
wm_item = agol.content.get("WM_ITEM_ID")
## create the webmap object
wm = WebMap(wm_item)
## get a list of the current layers.
## this is a list of dictionaries
current_lyrs = list(wm.layers)
## get the number of layers being added from teh view
num_view_lyrs = len(view_item.layers)
## add the layers in reverse order
for lyr in reversed(view_item.layers):
wm.add_layer(lyr)
## get the list of dictionaries for the layers just added
lyrs2grp = wm.layers[-num_view_lyrs:]
## define the group layer
## you can set the titke of the group layer to some other text
group_lyr = [{
"title" : view_item.title,
"layers" : lyrs2grp,
"layerType": "GroupLayer",
"visibilityMode": "independent"
}]
## create a new operationalLayers list
new_ol = current_lyrs + group_lyr
## set the operationalLayers property to be the new_ol list
wm.definition.operationalLayers = new_ol
## update the webmap item object
item_properties = {"text":wm.definition}
wm_item.update(item_properties=item_properties)
Python API 2.4.0 now supports Group Layers
Edits to your code for this to work in 2.4.0:
webmap_item = gis.content.get(webmap_id)
view_item = gis.content.get(view_id)
wm = Map(item=webmap_item)
wm.content.remove(0) #index of layer to remove
wm.update()
wm.content.add(view_item)
wm.update()