Select to view content in your preferred language

Create and populate group layers with feature classes

908
3
12-06-2023 09:23 AM
HusamAbuOqer
Emerging Contributor

Hello,

 

I am trying to create a Python script that creates several group layers with specific names on a pre-created aprx file (GIS Pro) and then iterates through the folders and adds each feature class to its corresponding group layer.

I have several trials now and I am unable to create the group layers with specific names.

The main issue is that I am unable to add the feature classes even to a pre-created group layer.

 

Tags (2)
0 Kudos
3 Replies
AlfredBaldenweck
MVP Regular Contributor

So, I was working on this the other day and it was a massive pain.

Below is a snippet from a larger script of mine. Given a file gdb, it'll add all the contents to a group layer named after said gdb.

This other thing too is that I had an impossible time trying to get "AddFeatureLayer" or whatever it is to work. Like I could create a layer but I couldn't move it because ??????? (Seriously Esri why is this so hard?). My solution here is to use addDataFromPath(), which will add a layer to your map. Then I feed it into my group layer, which for some reason duplicates it, so I just remove the layer that isn't in the group layer afterwards.

mp = arcpy.mp.ArcProProject("CURRENT").activeMap

out_ds = #path\to\your\gdb
outName = #the basename of your gdb. This made sense in context.

outGroup = mp.createGroupLayer(os.path.basename(outName))
arcpy.env.workspace = out_ds

for fc in arcpy.ListFeatureClasses():
    fcLay = mp.addDataFromPath(os.path.join(out_ds,fc))
    mp.addLayerToGroup(outGroup, fcLay)
    mp.removeLayer(fcLay)
for tb in arcpy.ListTables():
    fcLay = mp.addDataFromPath(os.path.join(out_ds,tb))
    mp.addTableToGroup(outGroup, fcLay)
    mp.removeTable(fcLay)
for fd in arcpy.ListDatasets():
    fdGroup = mp.createGroupLayer(fd, outGroup)
    arcpy.env.workspace = os.path.join(out_ds, fd)
    for fc in arcpy.ListFeatureClasses():
        fcLay = mp.addDataFromPath(os.path.join(out_ds, fd, fc))
        mp.addLayerToGroup(fdGroup, fcLay, "TOP")
        mp.removeLayer(fcLay)
    arcpy.env.workspace = out_ds

 

HusamAbuOqer
Emerging Contributor

It's a painful task to do!
Thank you so much, the first try worked to create a group layer and populate it.
I need to continue working on it as the code requires to create of multi-group layers and adding layers in different folders based on their names! 

0 Kudos
AlfredBaldenweck
MVP Regular Contributor

Yup! Check out the feature dataset section to see how to do that.