I have a geodatabase with several feature dataset and feature classes associated with it respectively. I would like to create a .mxd where the Table of contents consist of group layer and each group layer has several shapefile. The group layer name should be same as Feature dataset name.The feature classes in each feature dataset comes shapefiles with in that particular group layer as shown in figure.
Answer
The following code snippet works in ArcGIS 10.1+.
Note that creating a new mxd can't be done in arcpy, you need to reference an existing empty mxd. Also, I couldn't find a way of creating a new empty group layer in arcpy, so I created one in ArcMap and saved it to a .lyr file and used that in the code.
import os,arcpy
gdb=r'C:\TEMP\Default_1.gdb'
template_mxd = r'C:\Temp\empty.mxd'
template_group_layer = r'C:\Temp\empty_group.lyr'
output_mxd = r'C:\Temp\not_empty.mxd'
mxd=arcpy.mapping.MapDocument(template_mxd)
df = arcpy.mapping.ListDataFrames(mxd)[0]
groups={}
for path, dirs, files in arcpy.da.Walk(gdb):
#Any "folder" in a GDB is a Feature Dataset
#and there can only be a single level
for d in dirs:
#Add an empty group layer to ArcMap
lyr=arcpy.mapping.Layer(template_group_layer)
lyr.name=d
arcpy.mapping.AddLayer(df,lyr)
groups[d]=arcpy.mapping.ListLayers(mxd,d,df)[0]
for f in files:
fp=os.path.join(path,f)
dsc=arcpy.Describe(fp)
lyr=None
view=None
if dsc.dataType == 'FeatureClass':
lyr=arcpy.management.MakeFeatureLayer(fp,os.path.basename(fp))[0]
elif dsc.dataType == 'RasterDataset':
lyr=arcpy.management.MakeRasterLayer(fp,os.path.basename(fp))[0]
elif dsc.dataType == 'Table':
view=arcpy.management.MakeTableView(fp,os.path.basename(fp))[0]
else:continue
if path==gdb and lyr:
lyr.visible=False
arcpy.mapping.AddLayer(df,lyr)
elif view:
arcpy.mapping.AddTableView(df, view)
else:
d=os.path.basename(path)
arcpy.mapping.AddLayerToGroup(df, groups[d], lyr, "BOTTOM")
mxd.saveACopy(output_mxd)
No comments:
Post a Comment