4

I want to add a feature class within a Geodatabase to a map in ArcGIS Pro (1.4.1) using arcpy. I am converting some python code from ArcGIS Desktop to ArcGIS Pro.

This issue is very similar to:

However, instead of adding a feature class (or layer) to a map using the Python Window I am doing this from a Script within a Toolbox. I have included a code snippet below.

lyrTest = r"C:\data\test.gdb\Layer1" 
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprxMap = aprx.listMaps("MainMap")[0] 
lyrFile = arcpy.mp.LayerFile(lyrTest)
aprxMap.addLayer(lyrFile)

I get the following error message:

Traceback (most recent call last):
File "C:\data\AddLayers.py", line 5, in <module>    
aprxMap.addLayer(lyrTest)
File "c:\users\user\appdata\local\programs\arcgis\pro\Resources\arcpy\arcpy\utils.py", line 191, in fn_
return fn(*args, **kw)
File "c:\users\user\appdata\local\programs\arcgis\pro\Resources\arcpy\arcpy\_mp.py", line 1048, in addLayer
return convertArcObjectToPythonObject(self._arc_object.addLayer(*gp_fixargs((add_layer_or_layerfile, add_position), True)))
ValueError: C:\data\test.gdb\Layer1
Failed to execute (AddLayers).
4
+50

The addDataFromPath method on the Map object worked for me, as shown in code below.

lyrTest = r"C:\data\test.gdb\Layer1" 
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprxMap = aprx.listMaps("MainMap")[0] 
aprxMap.addDataFromPath(lyrTest)

and if you also need a Layer object from that data then change the last line to:

lyr = aprxMap.addDataFromPath(lyrTest)

See the ArcGIS Pro Help for Map class properties:

The addDataFromPath method provides a way to add a layer to a map in a similar way to how the Add Data From Path button works in the application; it places each layer based on layer weight rules and geometry type. For more precise layer placement control, refer to the moveLayer method.

1

I believe the function/method is expecting a layerFile (.lyr or .lyrx) and you are providing it was a featureclass (which some colloquially refer to as a layer to add to the confusion).

I believe your issue is that you are trying to add a layer file when you should be creating one and then adding it. if you do something like below it should work with your current set up.

aprxMap = map.listMaps()[0]    
file = mp.LayerFile("C:\Temp\deleteme.lyrx")
aprxMap.addLayer(file)

Otherwise you should use MakeFeatureLayer like below to add a Feature Class as a feature Layer and name it "PickMeAsTheAnswer"

arcpy.MakeFeatureLayer_management(lyrTest,"PickMeAsTheAnswer")

  • Thanks @bwp8nt, I agree the function/method was expecting and .lyr or .lyrx file rather than the other type layer ArcGIS Pro uses (formally referred to as a 'feature class'). ESRI sometimes don't make it very easy. – Nic Dec 30 '17 at 11:29

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.