Hello,
I am trying to add group layers to a map with ArcPy. I have seen old answers saying this is not possible, and suggesting instead to create a layer file with the groups already created. This will not work for me because the number of groups is not known in advance.
Is it possible to add group layers to a map in ArcPy?
Thanks
Solved! Go to Solution.
For ArcGIS Pro:
Create an empty group layer and save it, then run this:
empty_group_layer_file = arcpy.mp.LayerFile(r"H:\New Group Layer.lyrx")
active_map = arcpy.mp.ArcGISProject("current").activeMap
# In this example, I'll use a dict of {group_layer_name: [layers]} as input. Adjust according to your existing code.
group_layers = {
"Group Layer 1": [layer_1, layer_2],
"Group Layer 2": [layer_3, layer_4],
}
for group_name, layers in group_layers.items():
group = active_map.addLayer(empty_group_layer_file)[0]
group.name = group_name
for lyr in layers:
active_map.addLayerToGroup(group, lyr)
For ArcGIS Pro:
Create an empty group layer and save it, then run this:
empty_group_layer_file = arcpy.mp.LayerFile(r"H:\New Group Layer.lyrx")
active_map = arcpy.mp.ArcGISProject("current").activeMap
# In this example, I'll use a dict of {group_layer_name: [layers]} as input. Adjust according to your existing code.
group_layers = {
"Group Layer 1": [layer_1, layer_2],
"Group Layer 2": [layer_3, layer_4],
}
for group_name, layers in group_layers.items():
group = active_map.addLayer(empty_group_layer_file)[0]
group.name = group_name
for lyr in layers:
active_map.addLayerToGroup(group, lyr)
Thanks Johannes! After fixing a couple typos (AddLayer -> addLayer) I was able to use this to create new group layers.
this works in ArcMap too if you do the same but with an empty group .lyr file and make the appropriate changes to work in arcpy.mapping instead of arcpy.mp
After I got past the mental block of using Pro to create an empty LYRX file, this works. I was expecting line one to create the file for me. Thanks!