How to correctly populate an activeMap.addLayerToGroup() call?

929
3
03-28-2022 01:16 PM
EricEagle
Occasional Contributor III

UPDATED-- fixed the group layer reference at line 15; still doesn't work

I'm attempting to follow this answer:  https://community.esri.com/t5/arcgis-pro-questions/is-it-possible-to-create-a-new-group-layer-with/t...

But it is not working for me.  I have a script tool that performs various route solving problems using a defined OSRM instance.  The results return fine but tend to clutter up the table of contents.  My intent is to put the results of each run (lines, points) into its own group layer.

I can create the group layer without issue via an empty group layer .lyrx file that will be distributed with the release.

However, here's where I'm failing:

 

# At this point I have feature classes in
# a list that I iterate over to add to the map

grplyrpath = os.path.join(Path(os.path.dirname(__file__)).parent, "res")
gprlyrfile = os.path.join(grplyrpath, "group.lyrx")
grplyr = arcpy.mp.LayerFile(grplyrfile)
osrm_group = active_map.addLayer(grplyr)[0]
osrm_group.name = f"OSRM {now}"  # now is the script start-time in string

for idx, rfc in enumerate(route_fc_list):
    osrm_lyr = active_map.addDataFromPath(rfc)
    if idx == 0:  # First route is primary/fastest route
        osrm_lyr.name = "OSRM Route (Primary)"
        # then do bunch of symbology
        active_map.addLayerToGroup(osrm_group, osrm_lyr)

 

this earns me an error in addLayerToGroup

ValueError: <MappingLayerFileObject object at (memory address)>

 

I've also tried directly adding the feature classes to the group layer (which would be more efficient) but that failed too.

 

Can someone post a working example of how to prep a layer and add it into a group layer via arcpy?

0 Kudos
3 Replies
DonMorrison1
Occasional Contributor III

This works for me when I run it in the ArcGIS Pro python window

aprx = arcpy.mp.ArcGISProject('CURRENT')
active_map = aprx.activeMap
rfc = r'E:\CW_Hub\temp\CW_Boundary_2009\CW_Boundary_2009.shp'

grplyrfile = r'E:\CW_Hub\temp\Group layer.lyrx'
grplyr = arcpy.mp.LayerFile(grplyrfile)
osrm_group = active_map.addLayer(grplyr)[0]
osrm_lyr = active_map.addDataFromPath(rfc)
active_map.addLayerToGroup(osrm_group, osrm_lyr)
active_map.removeLayer(osrm_lyr)
0 Kudos
EricEagle
Occasional Contributor III

Thanks Don; maybe I am having trouble here but I don't see what I've done that is any different from what you've posted (except running it via script tool)... ideas?

0 Kudos
DonMorrison1
Occasional Contributor III

Right - it seems to be the equivalent.  Can you do something similar with your data and get it to work in the ArcGIS Pro python window? That might indicate a problem in your python environment.

0 Kudos