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

6068
3
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 Frequent 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

3 Replies
JohannesLindner
MVP Frequent 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
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
mTylerH
New Contributor II

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

0 Kudos