Is it possible to create a new group layer with arcpy?

1454
2
Jump to solution
06-15-2021 01:31 PM
Labels (1)
JesseTemplin2
New Contributor III

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

0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Regular Contributor

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)

 

 


Have a great day!
Johannes

View solution in original post

0 Kudos
2 Replies
JohannesLindner
MVP Regular Contributor

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)

 

 


Have a great day!
Johannes
0 Kudos
JesseTemplin2
New Contributor III

Thanks Johannes! After fixing a couple typos (AddLayer -> addLayer) I was able to use this to create new group layers.

0 Kudos