ArcPy – Adding Feature Class to Map in ArcGIS Pro Project

arcgis-proarcpylayers

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).

Best Answer

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.

Related Question