操作方法

操作方法:使用 Python 脚本将地理数据库中的图层放置到 ArcGIS Pro 地图上

Last Published: February 20, 2025

描述

在 ArcGIS Pro 中执行任何过程时,都会将要素添加到地图以实现可视化。 添加到打开的地图后,这些要素会自动转换为图层文件。 要使用 Python 脚本将地理数据库中的要素添加到地图,必须将该要素转换为图层文件。 因此,要在不打开 ArcGIS Pro 软件的情况下将要素放置到地图上,可在脚本中使用“创建要素图层”和“保存到图层文件”工具将所需要素从地理数据库转换为图层文件。

以下工作流描述了如何使用 Python 脚本向现有地图添加要素。

解决方案或解决方法

  1. 导入所需的模块。
import arcpy
  1. 指定工作空间和 ArcGIS Project 文件位置。
arcpy.env.workspace = r"<folder_location>\<geodatabase.gdb>"

project_path = r"<folder_location>\<project_name.aprx>"
aprx = arcpy.mp.ArcGISProject(project_path)
  1. 指定要在“创建要素图层”和“保存到图层文件”工具中使用的参数。
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
  1. 调用“创建要素图层”和“保存到图层文件”工具。
arcpy.management.MakeFeatureLayer(in_layer, "<output_file_name>")
arcpy.management.SaveToLayerFile("<output_file_name>" , layers_out)
  1. 参考现有图层将图层插入地图。
insertLyr = arcpy.mp.LayerFile(output_location)
m = aprx.listMaps("*")[0]
refLyr = m.listLayers("file_name")[0]
m.insertLayer(refLyr, insertLyr, "BEFORE")
  1. 保存工程文件。
aprx.save()
  1. 清除工程的锁定文件。
del aprx

以下代码块演示了完整脚本。

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

文章 ID: 000028522

接收通知并查找新问题或常见问题的解决方案

从我们全新的 AI 聊天机器人中获得简明答案和视频解决方案。

下载 Esri 支持应用程序

相关信息

发现关于本主题的更多内容

获取来自 ArcGIS 专家的帮助

联系技术支持部门

下载 Esri 支持应用程序

转至下载选项