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!去Solution.
For ArcGIS Pro:
创建一个空的组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:
创建一个空的组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.