HOW TO
Features are added to the map for visualization when performing any process in ArcGIS Pro. When added to an opened map, these features are automatically converted into a layer file. For a feature in a geodatabase to be added to a map using a Python script, the feature must be converted into a layer file. Therefore to place a feature onto a map without opening the ArcGIS Pro software, the Make Feature Layer and Save To Layer File tools are used in the script to convert the desired feature from a geodatabase into a layer file.
The following workflow describes how to add features to an existing map using a Python script.
import arcpy
arcpy.env.workspace = r"<folder_location>\<geodatabase.gdb>" project_path = r"<folder_location>\<project_name.aprx>" aprx = arcpy.mp.ArcGISProject(project_path)
layer = r"<folder_location>\<geodatabase.gdb>\<file_name>" layers_out = "<output_file_name>" output_location = r"<folder_location>\{}.lyrx".format(layers_out) #Same as project path
arcpy.management.MakeFeatureLayer(in_layer, "<output_file_name>") arcpy.management.SaveToLayerFile("<output_file_name>" , layers_out)
insertLyr = arcpy.mp.LayerFile(output_location) m = aprx.listMaps("*")[0] refLyr = m.listLayers("file_name")[0] m.insertLayer(refLyr, insertLyr, "BEFORE")
aprx.save()
del aprx
The code block below demonstrates the full script.
import arcpy arcpy.env.workspace = r"C:\USER\Desktop\Test\test.gdb" project_path = r"C:\USER\Desktop\Test\Test_Project.aprx" aprx = arcpy.mp.ArcGISProject(project_path) layer = r"C:\USER\Desktop\Test\test.gdb\Layer_Test" #The feature name in the geodatabase layers_out = "Layer_Test" #The file name for the output layer output_location = r"C:\USER\Desktop\Test\{}.lyrx".format(layers_out) arcpy.management.MakeFeatureLayer(in_layer, "Layer_Test") arcpy.management.SaveToLayerFile("Layer_Test" , layers_out) insertLyr = arcpy.mp.LayerFile(output_location) m = aprx.listMaps("*")[0] refLyr = m.listLayers("Existing_Layer")[0] m.insertLayer(refLyr, insertLyr, "BEFORE") #Insert the new layer onto the map before the specified existing layer aprx.save() del aprx #Close the project and delete the lock file
Article ID: 000028522
Get help from ArcGIS experts
Download the Esri Support App