Sorting Layers with Python

1347
1
05-12-2011 04:14 AM
chriss_
New Contributor II
Hi!

I want to write a code that sorts my layers in a map in a certain order. The order shall be exactly like in a "master.mxd" where i loaded all layers and sorted them. The tool shall be used for different maps so that not all layers might be in the map where i run the code.
In my mind there are the following steps.

import arcpy
#Make new lists called CurrentLyr and MasterLyr
CurrentLyr =[]
MasterLyr =[]
#Defining Map and Dataframe of Master map
mxd = arcpy.mapping.MapDocument(r"C:/Python/Master.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
#Append all Layers in the list
MasterLyr.append (arcpy.mapping.ListLayers(mxd, "", df):)
#Defining Map and Dataframe of CurrentMap
mxd = arcpy.mapping.MapDocument("Current")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
#Append all Layers in the list
CurrentLyr.append (arcpy.mapping.ListLayers(mxd, "", df):)
#Step through each Master layer
for i in MasterLyr:
#compare MasterLyr with CurrentLyr
  if cmp(MasterLyr,CurrentLyr)= true
#Add Layer to current map
arcpy.mapping.AddLayer(df, "", "bottom")
arcpy.RefreshActiveView()
arcpy.RefreshTOC()

Thats my first Python Code ever so please be patient.
Any ideas or pieces of code?

best regards

Chris
Tags (2)
0 Kudos
1 Reply
chriss_
New Contributor II
Hi!
So finally I made some progress in programming. But I am still not completely happy.
It works fine ,if there are only "normal" layers (raster, shape) BUT if I use GroupLayers it gets totally messed up. What happens is that the code "destroys" the group layer and converts it to a "normal" layer. This causes the longName of layers in the former grouplayer to change and my sorting Code is useless. GroupAnnotationLayers get messed up totally and several new singleannotation layers are generated.
Any idea how to access the grouplayer or any other samrt idea to solve this problem.
Thanks

Chris

p.s. here my code
import arcpy
mxd = arcpy.mapping.MapDocument("Current")
df = arcpy.mapping.ListDataFrames(mxd, "")[0]
mxd2 = arcpy.mapping.MapDocument(r"C:\Master\Master.mxd")
df2 = arcpy.mapping.ListDataFrames(mxd2, "")[0]
refLayer = arcpy.mapping.ListLayers(mxd,"",df)[1]
for lyr2 in arcpy.mapping.ListLayers(mxd2,"",df2):
   c=lyr2.longName
   d=lyr2.description
   MasterLayer=c+d
   print MasterLayer
   for lyr in arcpy.mapping.ListLayers(mxd,"",df):
      a=lyr.longName
      b=lyr.description
      moveLayer= a+b
      print moveLayer
      if MasterLayer==moveLayer:
         moveLayer=lyr
         arcpy.mapping.MoveLayer(df,refLayer,moveLayer, "After")
         refLayer=moveLayer
         print MasterLayer,moveLayer
                       
mxd.save()
del mxd
0 Kudos