Thursday, 7 July 2016

arcgis desktop - Use python to add layers to TOC


I've been battling with adding layers to the TOC for some time now. I have managed to single layers added but need to loop through a folder and add all layers. Shapefiles I cannot get to add at all. Only layer files. Below is the code of where I'm at:



for layer in shp_List:
mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]

outlayer = lyr
layerfile = os.path.join(base_Folder, lyr + ".lyr")

arcpy.MakeFeatureLayer_management(layer, outlayer)
arcpy.SaveToLayerFile_management(outlayer, layerfile, "ABSOLUTE")
addlayer = arcpy.mapping.Layer(layerfile)

arcpy.mapping.AddLayer(dataFrame, addlayer, "BOTTOM")



#addLayer = arcpy.mapping.Layer(layer)
#arcpy.mapping.AddLayer(dataFrame, addLayer, "BOTTOM")
#arcpy.RefreshTOC()
#arcpy.RefreshActiveView()
del addlayer, mxd


The above code will add each layer to the TOC, then infuriatingly removes it and adds the next one. When the whole script finishes there is nothing left in the TOC. I've tried adding this script to a model and creating a derived output parameter which is then added as a model parameter with "add to display" checked. I've also checked the geoprocessing options to make sure the box to add to display is checked. I'm running Arc 10 (no service packs). Can anyone help?



Answer



You need to create the MapDocument and DataFrame objects outside of the loop that runs through your layers. Otherwise you are starting with the original map each time.


so i will correct in this code:


mxd = arcpy.mapping.MapDocument("CURRENT")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]

for layer in shp_List:

outlayer = layer + "_lyr"

layerfile = os.path.join(base_Folder, layer + ".lyr")

arcpy.MakeFeatureLayer_management(layer, outlayer)
arcpy.SaveToLayerFile_management(outlayer, layerfile, "ABSOLUTE")
addlayer = arcpy.mapping.Layer(layerfile)
arcpy.mapping.AddLayer(dataFrame, addlayer, "BOTTOM")



#addLayer = arcpy.mapping.Layer(layer)

#arcpy.mapping.AddLayer(dataFrame, addLayer, "BOTTOM")
arcpy.RefreshTOC()
arcpy.RefreshActiveView()
#del addlayer, mxd

To loop in a list of mxd files in the same folder of the script, you can do it like this :


for mxd_name in mxd_names:
mxd = arcpy.mapping.MapDocument(os.path.dirname(os.path.realpath(__file__))+"\\"+mxd_name+".mxd")
dataFrame = arcpy.mapping.ListDataFrames(mxd, "*")[0]

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...