4

我正在尝试使用 Python 自动化 ArcGIS Desktop 中的各种任务(通常使用 ArcMap),并且我一直需要一种将形状文件添加到当前地图的方法。(然后对其进行处理,但那是另一回事了)。

到目前为止,我能做的最好的事情是使用以下内容将图层文件添加到当前地图(“addLayer”是图层文件对象):

def AddLayerFromLayerFile(addLayer):
 import arcpy
 mxd = arcpy.mapping.MapDocument("CURRENT")
 df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
 arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
 arcpy.RefreshActiveView()
 arcpy.RefreshTOC()
 del mxd, df, addLayer

但是,我的原始数据总是形状文件,所以我需要能够打开它们。(等效地:将形状文件转换为图层文件而不打开它,但我不想这样做)。

4

2 回答 2

6

变量“theShape”是要添加的形状文件的路径。

import arcpy
import arcpy.mapping
# get the map document 
mxd = arcpy.mapping.MapDocument("CURRENT")  

# get the data frame 
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]  

# create a new layer 
newlayer = arcpy.mapping.Layer(theShape)  

# add the layer to the map at the bottom of the TOC in data frame 0 
arcpy.mapping.AddLayer(df, newlayer,"BOTTOM")

# Refresh things
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, newlayer
于 2011-11-24T18:02:55.113 回答
1

最近在为一个类似的任务苦苦挣扎,初步使用了识别地图文档,识别数据框,创建图层,添加图层到地图文档的方法。有趣的是,只要从当前地图文档中调用它,这一切都可以使用以下命令来完成。

# import modules
import arcpy

# create layer in TOC and reference it in a variable for possible other actions
newLyr = arcpy.MakeFeatureLayer_managment(
    in_features, 
    out_layer
)[0]

制作要素图层需要两个输入,即输入要素和输出图层。输入要素可以是任何类型的要素类或图层。这包括 shapefile。输出层是要出现在内容列表中的层的名称。

此外,制作要素图层可以接受 where 子句以在创建时创建定义查询。这通常是我实现它的方式,当需要快速创建许多具有不同定义查询的层时。

最后,在上面的代码片段中,虽然不是必需的,但我演示了如何使用工具输出的结果填充变量,以便可以在脚本后面需要时使用 arcpy.mapping 在目录中操作图层. 每个工具都返回一个结果对象。可以使用 getOutput 方法访问结果对象输出,但也可以使用您感兴趣的结果属性的索引来访问它,在这种情况下,输出位于索引 0 处。

于 2014-07-23T13:01:06.657 回答