摘要
用于访问地图文档 (.mxd) 属性和方法。对于此对象的引用对大多数地图脚本操作都十分重要。
说明
MapDocument 对象通常是在地图自动化脚本中创建的首批对象引用之一,因为它是许多 arcpy.mapping 函数的必要参数。通过 MapDocument 对象,您基本上可以访问地图文档中的几乎所有其他对象(例如,数据框、图层、页面布局元素)。MapDocument 对象用于访问 ArcMap 的地图文档属性对话框中的大部分地图文档属性(文件 > 地图文档属性)。该对象还包含管理地图文档缩略图的方法和保存地图文档的方法,这些方法可在 ArcMap 的“文件”菜单中找到。
使用 MapDocument 函数创建 MapDocument 对象的方法有两种。第一种,也是首推方法,即提供磁盘上地图文档 (.mxd) 位置的系统路径。该方法最为常用,因为随后可在 ArcGIS 应用程序外部运行脚本。引用磁盘上的特定地图文档这种方法可对脚本执行方式予以更多控制,因为给定脚本在某些地图文档上可能无法正常运行。
第二种方法是将 CURRENT 关键字作为 MapDocument 函数的输入参数。该方法仅适用于 ArcMap 应用程序内部,因为 MapDocument 对象引用当前加载到 ArcMap 应用程序中的地图文档。想要快速测试和了解 Python 窗口内的脚本功能和命令语法时,使用 CURRENT 会很有帮助。您可以从了解 Python 窗口中的语法入手,然后将那些代码行粘贴到保存在磁盘上的更永久的脚本中。
使用 CURRENT 关键字的脚本工具必须在 ArcMap 内运行(从自定义菜单或“目录”窗口)。如果在 ArcCatalog 应用程序内运行使用 CURRENT 的脚本工具,将无法正确执行。出于同样的原因,如果脚本工具含有带 CURRENT 引用的验证脚本,则在您尝试从 ArcCatalog 编辑验证脚本时可能会出现错误。确保在 ArcMap 目录窗口内编辑脚本工具的验证代码。
要使用脚本工具中的 CURRENT 关键字,必须禁用后台处理。后台处理会按照在 ArcGIS 外部运行独立脚本的方式运行所有脚本。为此,启用后台处理时 CURRENT 将不可用。有一个新的脚本工具选项称为始终在前台中运行,可确保脚本工具在前台中运行,即使启用了后台处理也是如此。
理解变量在脚本环境中如何引用 MapDocument 对象非常重要,特别是当您将结果保存到新文件中时。您必须理解当您最初创建引用 MapDocument 对象的变量时,它始终会指向磁盘上或当前内存中的原始地图文档(通过 CURRENT)。在 ArcMap 应用程序中,如果您以一个新文件位置执行 SaveAs,则所有后续更改都会定向到该新文件。在脚本环境中,这是无法实现的,因此,不提供 saveAs 方法。MapDocument 类具有 save 和 saveACopy 方法,用于管理地图文档的修改。
使用 CURRENT 地图文档时,如果使用脚本修改某些地图文档元素的外观(例如,更改图层名称、数据框范围等),地图可能不会使用每一行已执行的代码进行更新。要刷新地图文档以反映更改,请使用 RefreshActiveView 或 RefreshTOC 函数。这些函数将分别刷新地图显示或页面布局和内容列表。仅当您想要看到更新的应用程序时,才需要刷新函数。在不使用这些函数的情况下,Arcpy.mapping 导出、保存和打印函数将会生成预期的更新结果。
由于用户名和密码信息未保存在图层文件内或地图文档内,所以地图文档或图层文件内的一些图层可能受密码保护。打开包含这些图层的地图文档时将会提示用户输入相应的信息。默认情况下,arcpy.mapping 脚本环境将在执行过程中禁止使用这些对话框,但这意味着这些图层的数据源将被视为已经损坏。换言之,受保护的图层将不会在任何输出中进行渲染。如果希望适当地渲染这些图层,则应采取如下做法。首先,将用户名和密码信息随图层一同保存。其次,CreateArcSDEConnectionFile 地理处理函数允许您在内存中创建持久的连接。如果在使用 MapDocument 函数打开地图文档 (.mxd) 或使用 Layer 函数打开图层文件之前使用该命令,那么 SDE 图层将得到渲染。目前尚没有针对受保护的 Web 服务的操作方法。
引用 MapDocument 对象的变量将会锁定地图文档文件。最好在脚本结尾或在 try/except 语句中使用 Python del 命令来移除地图文档对象引用。
通常要求更改地图文档中的数据源。MapDocument 对象中有两种方法可以实现此目的。findAndReplaceWorkspacePaths 方法用于替换部分或全部的图层或表格工作空间路径。replaceWorkspaces 方法允许您更改路径和工作空间类型。有关详细说明、参数信息、案例和编码示例,请参阅使用 arcpy.mapping 更新和修复数据源帮助主题。
语法
MapDocument (mxd_path)
参数 | 说明 | 数据类型 |
mxd_path | A string that includes the full path and file name of an existing map document (.mxd) or a string that contains the keyword CURRENT. | String |
属性
属性 | 说明 | 数据类型 |
activeDataFrame (只读) | Returns a DataFrame object that represents the currently active data frame in a map document (.mxd). The activeDataFrame property will return the appropriate data frame even if the map document is in page layout view. If you want to set the active data frame, use the activeView property. | DataFrame |
activeView (可读写) | Provides the ability to set or get a map document's active view to either a single data frame or the page layout. The property works with a string that represents the active data frame name or the PAGE_LAYOUT keyword. If activeView is set to PAGE_LAYOUT and the map document is saved, the next time the map document is opened, it will be opened in layout mode. If activeView is set to a data frame name and the map document is saved, the next time the map document is opened, it will be opened in data view, and that particular data frame will be the active data frame. | String |
author (可读写) | Provides the ability to either get or set the map document's author information. | String |
credits (可读写) | Provides the ability to either get or set the map document's credits or copyright information. | String |
dataDrivenPages (只读) | Returns a DataDrivenPages object that can then be used to manage the pages in a Data Driven Pages enabled map document. | DataDrivenPages |
dateExported (只读) | Returns a Python datetime object that reports the date the last time the map document was exported. This value is only current if the map document was saved after the map was exported. | DateTime |
datePrinted (只读) | Returns a Python datetime object that reports the date the last time the map document was printed. This value is only current if the map document was saved after the map was printed. | DateTime |
dateSaved (只读) | Returns a Python datetime object that reports the date the last time the map document was saved. | DateTime |
description (可读写) | Provides the ability to either get or set the map document's description information. | String |
filePath (只读) | Returns a string value that reports the fully qualified map document path and file name. | String |
hyperlinkBase (可读写) | Provides the ability to either get or set the base path or URL used for field-based hyperlinks to documents or URLs. | String |
isDDPEnabled (只读) | Returns True if the map document is Data Driven Pages enabled. | Boolean |
pageSize (只读) | Provides the ability to get the layout's page size. It returns a named tuple with the properties width and height. The following script shows a few different techniques to print a map document's page width and height.
| tuple |
relativePaths (可读写) | Provides the ability to control if a map document stores relative paths to the data sources. A value of True sets relative paths; a value of False sets full paths to the data sources. | Boolean |
summary (可读写) | Provides the ability to either get or set the map document's summary information. | String |
tags (可读写) | Provides the ability to either get or set the map document's tag information. Separate tags with a single comma (,). | String |
title (可读写) | Provides the ability to either get or set the map document's title information. | String |
方法概述
方法 | 说明 |
deleteThumbnail () | Deletes a map document's (.mxd) thumbnail image |
findAndReplaceWorkspacePaths (find_workspace_path, replace_workspace_path, {validate}) | Finds old workspace paths and replaces them with new paths for all layers and tables in a map document (.mxd) |
makeThumbnail () | Creates a map document's (.mxd) thumbnail image |
replaceWorkspaces (old_workspace_path, old_workspace_type, new_workspace_path, new_workspace_type, {validate}) | Replaces an old workspace with a new workspace for all layers and tables in a map document (.mxd); also provides the ability to switch workspace types (for example, replace a file geodatabase data source with an SDE data source). |
save () | Saves a map document (.mxd) |
saveACopy (file_name, {version}) | 可选择将地图文档 (.mxd) 保存为新文件或较早版本。 |
方法
deleteThumbnail ()
This performs the same operation as clicking the Delete Thumbnail button on the File > Map Document Properties dialog box in ArcMap.
findAndReplaceWorkspacePaths (find_workspace_path, replace_workspace_path, {validate})
参数 | 说明 | 数据类型 |
find_workspace_path | A string that represents the workspace path or connection file you want to find. If an empty string is passed, then all workspace paths will be replaced with the replace_workspace_path, depending on the value of the validate parameter. | String |
replace_workspace_path | A string that represents the workspace path or connection file you want to use to replace. | String |
validate | If set to True, a workspace will only be updated if the replace_workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set all workspaces to match the replace_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the layer and table's data sources would be broken. (默认值为 True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and Fixing Data Sources with arcpy.mapping help topic.
makeThumbnail ()
This performs the same operation as clicking the Make Thumbnail button in the File > Map Document Properties dialog box in ArcMap.
replaceWorkspaces (old_workspace_path, old_workspace_type, new_workspace_path, new_workspace_type, {validate})
参数 | 说明 | 数据类型 |
old_workspace_path | A string that represents the workspace path or connection file you want to find. If an empty string is passed, then all workspace paths will be replaced with the new_workspace_path, depending on the value of the validate parameter. | String |
old_workspace_type | A string keyword that represents the workspace type of the old data to be replaced. If an empty string is passed, multiple workspaces can be redirected into one workspace.
| String |
new_workspace_path | A string that represents the new workspace path or connection file. | String |
new_workspace_type | A string keyword that represents the workspace type that will replace the old_workspace_type.
| String |
validate | If set to True, a workspace will only be updated if the new_workspace_path value is a valid workspace. If it is not valid, the workspace will not be replaced. If set to False, the method will set all workspaces to match the new_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the data sources would be broken. (默认值为 True) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and Fixing Data Sources with arcpy.mapping help topic.
save ()
This performs the same operation as File > Save in ArcMap.
saveACopy (file_name, {version})
参数 | 说明 | 数据类型 |
file_name | A string that includes the location and name of the output map document (.mxd). | String |
version | A string that sets the output version number. The default value will use the current version.
(默认值为 None) | String |
此函数的作用与 ArcMap 中的文件 > 保存副本操作结果相同。早期版本的软件中不支持的功能将从新保存的地图文档中移除。在独立脚本中调用 saveACopy 时,将不会移除文档冗余。这是因为如果从应用程序中运行独立 Python 脚本,则该脚本将采用不同方式来访问地图文档。
代码示例
MapDocument 示例 1
以下脚本在地图文档中为每个数据框创建一个单独的 MXD 文件。输出地图文档将保存在数据视图模式中,这样,打开每个地图文档时,相应的数据框将变成活动数据框。该脚本还会设置每个输出地图文档的标题属性。由于此脚本使用地图文档的系统路径,因此,它可以在 ArcMap 应用程序外执行。注:Python 字符串不能以反斜线结尾,即使该字符串以 r 开头也是如此。您必须使用双反斜线。将动态文件名称附加到文件夹路径时,这一点很重要。
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
for df in arcpy.mapping.ListDataFrames(mxd):
mxd.activeView = df.name
mxd.title = df.name
mxd.saveACopy(r"C:\Project\Output\\" + df.name + ".mxd")
del mxd
MapDocument 示例 2
以下脚本演示如何在 Python 窗口中使用 CURRENT 关键字。此示例将会更新首个数据框的名称,并刷新内容列表,从而可在应用程序中看到更改。将以下代码粘贴到一个新 ArcMap 文档的 Python 窗口中。
mxd = arcpy.mapping.MapDocument("CURRENT")
arcpy.mapping.ListDataFrames(mxd)[0].name = "New Data Frame Name"
arcpy.RefreshTOC()
del mxd
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
... arcpy.mapping.ListDataFrames(mxd)[0].name = "New Data Frame Name"
... arcpy.RefreshTOC()
... del mxd
...
MapDocument 示例 3
下面是另一个简单脚本的示例,用于演示在 Python 窗口中使用 CURRENT 关键字。每一个图层名称都会打印到 Python 窗口中。如果您维护了正确的缩进,也可以进行循环。与上述示例类似,将以下代码粘贴到 Python 窗口中。
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):
print lyr.name
del mxd
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
... for lyr in arcpy.mapping.ListLayers(mxd):
... print lyr.name
... del mxd
...
MapDocument 示例 4
以下脚本将在打开需要输入密码的地图文档前,通过在内存中创建 SDE 连接确保适当地渲染受保护图层。此脚本简单地定义了连接信息并将地图文档导出至 PDF 文件。最好在脚本关闭之前从内存中删除此引用。
import arcpy, os
#Remove temporary connection file if it already exists
sdeFile = r"C:\Project\Output\TempSDEConnectionFile.sde"
if os.path.exists(sdeFile):
os.remove(sdeFile)
#Create temporary connection file in memory
arcpy.CreateArcSDEConnectionFile_management(r"C:\Project\Output", "TempConnection", "myServerName", "5151", "myDatabase", "DATABASE_AUTH", "myUserName", "myPassword", "SAVE_USERNAME", "myUser.DEFAULT", "SAVE_VERSION")
#Export a map document to verify that secured layers are present
mxd = arcpy.mapping.MapDocument(r"C:\Project\SDEdata.mxd")
arcpy.mapping.ExportToPDF(mxd, r"C:\Project\output\SDEdata.pdf")
os.remove(sdeFile)
del mxd