How to add a new Group Layer using arcpy

7728
5
10-14-2011 05:25 AM
MattSiple
New Contributor III
I am trying to create a layer structure that looks something like this:

Food
   [INDENT] - Fruit
          [INDENT]-Apple
             [INDENT]<feature layers for Apples 1>
              <feature layers for Apples 2>[/INDENT][/INDENT]
          [INDENT]-Apricots
               [INDENT]<features layer for Apricots 1>
              <features layer for Apricots 2>[/INDENT][/INDENT]
etc...[/INDENT]


So what I am looking for is something that allows me to create a "layer group". Since there is not a "layer group tool" I thought I would just create one in python. That is where I am having trouble.

I can use addLayer to add a .lyr file but the only adds a layer to an existing "layer group". Can anyone tell me how to create a layer group? (other than in the GUI) Is there anyway to accomplish this that I am not seeing?

Thanks in advance.
-matt
Tags (2)
0 Kudos
5 Replies
JeffBarrette
Esri Regular Contributor
This is not possible with arcpy.mapping.  You would need to author the group structure ahead of time.  You could then use arcpy.mapping.AddLayer and arcpy.mapping.AddLayerToGroup to insert layers into your mxd.

Jeff
0 Kudos
KristinaGrace
New Contributor II
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "County Maps")[0]
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "24000 Scale Data", df)[0]
addLayer = arcpy.mapping.Layer(r"C:\Project\Data\StreetsWithLabels.lyr")
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM")
mxd.saveACopy(r"C:\Project\Project2.mxd")
del mxd, addLayer

That works, except a layer is only added to a group layer in the new mxd - C:\Project\Project2.mxd - not the current mxd if you are using the Python window from within ArcMap.
0 Kudos
MathewCoyle
Frequent Contributor
I think you'd want
mxd.save()

Instead of
mxd.saveACopy()
0 Kudos
KristinaGrace
New Contributor II
That's the weird thing: that doesn't work.
I've also tried to refresh the view and TOC but this must be something to do with the group layer...

arcpy.RefreshActiveView()
arcpy.RefreshTOC()
0 Kudos
KristinaGrace
New Contributor II
Strangely, it works now
0 Kudos