I am trying to add layers from the fields of a reference layer using select by location and a cursor. Also, want to prompt the user with a message box asking if they want to add the selected by location. I am able to print string value from the reference layer when the user responds with "Yes" with the message box, but get an error when passing the string value as a path using "arcpy.mapping.addLayer".

def onMouseDownMap(self, x, y, button, shift):     
    mxd = arcpy.mapping.MapDocument("CURRENT")
    df = arcpy.mapping.ListDataFrames(mxd,"*")[0]
    #layer path
    lyr1 = arcpy.mapping.Layer("C:\ArcGis\Aerial_Imagery.lyr")
    #Add Layer
    arcpy.mapping.AddLayer(df, lyr1, "TOP")

    point = arcpy.Point(x, y)
    ptGeometry = arcpy.PointGeometry(point)
    #Select layer by points/mouse down on map
    arcpy.SelectLayerByLocation_management("Aerial_Imagery.lyr", "INTERSECT", ptGeometry)
    #cursor to display selected layers on field name "Layer_Path"
    cursor = arcpy.SearchCursor("Aerial_Imagery.lyr")
    field = "Layer_Path"
    for row in cursor:
        selpath = (row.getValue(field))
        message = "Would you like to add this Imagery:" + selpath
        Addbutton = pythonaddins.MessageBox(message, "Imagery Finder", 4)
        if Addbutton == "Yes":
            addlyr = arcpy.mapping.Layer(selpath)
            arcpy.mapping.AddLayer(df, addlyr, "TOP")#this breaks

            print selpath #this works

            pythonaddins.MessageBox("this is the answer to NO", "no answer", 0)

   #Remove Layer
    for lyr in arcpy.mapping.ListLayers(mxd, "Aerial_Imagery.lyr"):
        #print "Remove Layer", lyr
        arcpy.mapping.RemoveLayer(df, lyr)

    #Refresh view and TOC
  • Please tell us exactly what the error message says.
    – whuber
    Apr 14, 2014 at 16:44

1 Answer 1


Code looks OK to me so I guess its down to formatting of the string especially with "\" or "/" or "\\" .

This line:

lyr1 = arcpy.mapping.Layer("C:\ArcGis\Aerial_Imagery.lyr")

should really be:

lyr1 = arcpy.mapping.Layer(r"C:\ArcGis\Aerial_Imagery.lyr")

or it could be:

lyr1 = arcpy.mapping.Layer("C:\\ArcGis\\Aerial_Imagery.lyr")

So the full path that you are extracting out of image catalog layer should be formatted correctly. A simple find and replace of "\" with "\\" will work.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.