Add Layer Error

362
3
11-09-2012 10:32 AM
MaryM
by
Occasional Contributor
I am setting up a file to format a map template.  I am stuck at the Add Layer section.  I have a dictionary which is layer name:layer path.  I want to grab all the layer paths and add them as layers to the map template.  How can I fix my code?

TemplateLayers=(r"\\...\TemplateLayers.txt")
lyrDict={}
with open (TemplateLayers) as f:
    for line in f:
        (key,val)=line.split(",")
        lyrDict[(key)]=val
f.close()

print lyrDict

#Step 2: Pull the layers into the MXD at the bottom of the data frame from the dictionary.
for val in lyrDict.values():
    arcpy.mapping.AddLayer("",(val),"Bottom") 
I get: Runtime error <type 'exceptions.AssertionError'>:
When I print my dictionary it looks like this:
{'Roads':'\\\\filepath\\filename.lyr',etc....}
Tags (2)
0 Kudos
3 Replies
KimOllivier
Occasional Contributor III
You have to create a layer object from the pathname and then
specify the DataFrame that you are adding the layer object into.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "New Data Frame")[0]
addLayer = arcpy.mapping.Layer(r"C:\Project\Data\Orthophoto.lyr")
arcpy.mapping.AddLayer(df, addLayer, "BOTTOM")
0 Kudos
MaryM
by
Occasional Contributor
I have the path to the layer, I can cat the object arcpy.mapping... in front of all of them for each.  Does addLayer have to be referenced to a single variable or can it be referenced to a path name?
0 Kudos
ArkadiuszMatoszka
Occasional Contributor II
AddLayer takes 3 arguments:
AddLayer (data_frame, add_layer, {add_position})

where data_frame must be instance of arcpy.mapping.DataFrame, add_layer must be instance of arcpy.Layer.
All you have to do is define data frame of mxd and create arcpy.Layer()'s from paths so:
TemplateLayers=(r"\\...\TemplateLayers.txt")
lyrDict={}
with open (TemplateLayers) as f:
    for line in f:
        key,val=line.split(",")
        lyrDict[key]=val
f.close()

print lyrDict
mxd = arcpy.mapping.MapDocument('path\\to\\mxd.mxd')
df = arcpy.mapping.ListDataFrames(mxd)[0]
#Step 2: Pull the layers into the MXD at the bottom of the data frame from the dictionary.
for val in lyrDict.values():
    arcpy.mapping.AddLayer(df,arcpy.Layer(val),"Bottom")

That should do.
Regards
Arek
0 Kudos