Monday, 24 October 2016

layers - Adding feature class to Map in CURRENT project using ArcPy in ArcGIS Pro?


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

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.



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