Layer

サマリ

Provides access to layer properties and methods. It can either reference layers in a map document (.mxd) or layers in a layer (.lyr) file.

説明

The Layer object is essential for managing layers that reside within a map document (mxd) or within a layer (lyr) file. The layer object provides access to many of the common layer properties found in ArcMap's Layer Properties dialog box and it also provides methods for saving layer files. In addition to the Layer constructor function, the ListLayers function also provides the ability to get a reference to a Layer object. The ListLayers function is ideal for finding and referencing specific layers in a map document or layer file.

There are numerous types of layers and not all of them support the same set of properties. For example, a feature layer supports a definition query whereas a raster layer does not, but a raster catalog does. Rather than having to work with different, individual layer objects for all possible layer types and property combinations, a supports method is available to help identify which layer types support which individual layer properties. The supports method gives you the ability to test if the layer supports a property before trying to get or set its value on a layer type that doesn't support it, therefore reducing the need for additional error trapping.

There are essentially three categories of layers in a map document: feature layers, group layers, and raster layers. The isFeatureLayer, isGroupLayer, and isRasterLayer properties that work with the supports method allow you to identify or isolate the majority of layer types but not all layer types. There are a few specialized layers and datasets that don't fall into one of these three categories: annotation subclasses, dimension features, network datasets, terrain datasets, topology datasets, and so on. In these cases you may need to test other properties to isolate a layer of interest before doing something to it.

Not all layer properties are accessible through the Layer object. There are many properties available in the ArcMap Layer Properties dialog box that are not exposed to the arcpy scripting environment (e.g., scale ranges, display properties, field aliases, symbology, and so on). The UpdateLayer function allows you to replace all layer properties available in ArcMap's Layer Properties dialog box using a layer (.lyr) file that contains the customizations.

Group layers and other sublayers (e.g., annotation classes) are treated just like ordinary layers. The ListLayers function returns index values that are generated from top to bottom as they appear in the table of contents or the way they appear in a layer (.lyr) file. The same applies if a group layer is within another group layer. For example, a map document with a single group layer that contains three sublayers will return a list of four layer names, the group layer being the first and the three sublayers being the second, third, and fourth. There are two ways of determining if a layer is a group layer. First you can check to see if the layer supports the isGroupLayer property. Second, you can evaluate the longNameproperty. A layer's longName will include the group name in addition to the layer name. For example, a layer named Layer1 in a group layer named Group1 will have a longNamevalue of Group1\Layer1. If the name value is equal to longName value, then the layer is not a group layer or the layer is not inside a group layer.

Some layers within a map document or layer file may be password protected because the user and password information is not saved within the layer file or map document. Map documents that contain these layers will prompt the user to enter the appropriate information while the document is opening. The arcpy.mapping scripting environment will, by default, suppress these dialog boxes during execution but that means that the layers will be treated as though they have broken data sources. In other words, secured layers will not be rendered in any output. If it is necessary for these layers to render appropriately, then there are a couple of options. First, save the user name and password information with the layers. Second, the CreateArcSDEConnectionFile geoprocessing function allows you to create a connection that is persisted in memory. If this command is used prior to opening a map document (.mxd) with the MapDocument function or a layer file with the Layer function, then SDE layers will render. Currently, there is no alternative for secured web services.

The variable that references the MapDocument object will place a lock on the (.mxd) file. It is good practice to remove the object reference using the Python del command at the end of a script or within a try/except statement.

Changing a layer's data source is a common requirement. There are two methods on the Layer object that help with this. The findAndReplaceWorkspacePath method is intended for replacing part or all of a layer's workspace path. The replaceDataSource method allows you to change a layer's workspace and source dataset. For more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.

構文

Layer (lyr_file_path)
パラメータ説明データ タイプ
lyr_file_path

A string that includes the full path and file name of an existing layer (.lyr) file.

String

プロパティ

プロパティ説明データ タイプ
brightness
(読み書き)

Provides the ability to get or set the brightness value. The default, normal brightness, is 0%. Enter any value between +100% and -100%. Enter a plus or minus sign to the left of the value to specify whether it is above or below 0. Not all layers support the brightness property (for example, group layers, feature layers), so it is good practice to test for this ahead of time using the supports method.

Integer
contrast
(読み書き)

Provides the ability to get or set the contrast value. The default, neutral contrast, is 0%. Enter any value between +100% and -100%. Enter a plus or minus sign to the left of the value to specify whether it is above or below 0. Not all layers support the contrast property (for example, annotation layers, fabric layers), so it is good practice to test for this ahead of time using the supports method.

Integer
credits
(読み書き)

Provides the ability to either get or set the map document's credits or copyright information.

String
datasetName
(読み取り専用)

Returns the name of the layer's dataset the way it appears in the workspace, not in the TOC. Not all layers support the datasetName property (for example, Web services), so it is good practice to test for this ahead of time using the supports method.

String
dataSource
(読み取り専用)

Returns the complete path for the layer's data source. It includes the workspacePath and the datasetName properties combined. Not all layers support the dataSource property (for example, annotation classes, Web services), so it is good practice to test for this ahead of time using the supports method.

String
definitionQuery
(読み書き)

Provides the ability to get or set a layer's definition query. Not all layers support the definitionQuery property (for example, raster layers, group layers), so it is good practice to test for this ahead of time using the supports method.

String
description
(読み書き)

Provides the ability to either get or set the layer's description information. Not all layers support the description property (for example, topology layers), so it is good practice to test for this ahead of time using the supports method.

String
isFeatureLayer
(読み取り専用)

Returns True if a layer is a feature layer.

Boolean
isGroupLayer
(読み取り専用)

Returns True if a layer is a group layer.

Boolean
isRasterizingLayer
(読み取り専用)

Returns True if a layer will cause rasterization of other vector layers in the data frame when the map is printed or exported. Rasterization of vector layers during output most often occurs when layer transparency is used but can also happen when a layer has raster-based picture symbols or field-based transparency.

Boolean
isRasterLayer
(読み取り専用)

Returns True if a layer is a raster layer.

Boolean
labelClasses
(読み書き)

Provides access to a layer's label class properties by returning a list of LabelClass objects. Individual LabelClass object properties can be read and/or modified and written back to the layer. Not all layers support the labelClasses property (for example, raster layers, annotation layers), so it is good practice to test for this ahead of time using the supports method.

LabelClass
longName
(読み取り専用)

This property is valuable when trying to determine whether a layer belongs to a group layer. If a layer does not belong to a group layer, the long name will equal the layer name. If a layer does belong to a group layer, the group layer structure will be included in the long name. For example, the name of a layer nested inside a group layer within another group layer may look something like Group1\Group2\LayerName. All layer types support this property.

String
name
(読み書き)

Provides the ability to set or get the name of a layer the way it would appear in the ArcMap table of contents. Spaces can be included. All layer types support this property.

String
serviceProperties
(読み取り専用)

Provides access to connection information for ArcSDE and Web service layers. The returned results are dictionary key-value pairs. There are two different dictionaries returned based on the type of layer. The first is for ArcSDE connections, and the second is for all Web service layer types. The Web services dictionary contains keys that work for all service layer types and also includes specific keys that work for only a particular Web service type (for example, WMS has a key called WMSTitle). Either your script can check the ServiceType key before evaluating specific keys or you can use the get method that allows you to bypass keys that are not available. Not all layers support the serviceProperties property (for example, layers that are not ArcSDE or Web service layers), so it is good practice to test for this ahead of time using the supports method.

Keys for an ArcSDE dictionary

  • ServiceTypeThe property displaying the type of service. This will only be SDE for ArcSDE layer types.
  • ServerThe name or IP address of the computer where the ArcSDE geodatabase is located.
  • ServiceThe name or port number of the process running on the ArcSDE server.
  • DatabaseThe name of the enterprise RDBMS database. This is not required when using Oracle.
  • UserNameA user account. This will be blank if using operating system authentication.
  • AuthenticationModeGeodatabase or operating system authentication.
  • VersionThe version of the geodatabase to which you are connecting.

Keys for a Web service dictionary

  • ServiceTypeProperty displaying the type of service. These include ImageServer, IMS, MapServer, TiledInternetLayer, WMS, and WCS.
  • URLProperty displaying the URL to the service. If the connection to ArcGIS Server is through a local area network (LAN), this value will be null.
  • ServerProperty displaying the server name. If the connection to ArcGIS Server is through the Internet (HTTP), this value will be null.
  • UserNameProperty displaying the user name used to access a secured service. If the service is not password protected, this property will be null.
  • ServiceNameIMS service layers only. Property displays the name of the IMS service.
  • WMSNameWMS service layers only. Property displays the text string for the WMS service used for machine to machine communication.
  • WMSTitleWMS service layers only. Property displays the description title string for the WMS service.
  • NameWMS service layers only. Property displays the text string for the WMS layer used for machine to machine communication.
  • TitleWMS service layers only. Property displays the description title string for the WMS layer.

Dictionary
showLabels
(読み書き)

Controls the display of labels for a layer. If set to True, labels will display; if set to False, labels will not be drawn. Not all layers support the showLabels property (for example, raster layers, annotation layers), so it is good practice to test for this ahead of time using the supports method. Layer types that support the showLabels property also support the labelClasses property.

Boolean
transparency
(読み書き)

Provides the ability to get or set the transparency value. This enables you to "see through" a layer to the layers underneath. Type 0 if you don't want a layer to be transparent. A transparency value of more than 90% usually results in the layer not being drawn at all. Not all layers support the transparency property (for example, fabric group layers, Web service sublayers), so it is good practice to test for this ahead of time using the supports method.

Integer
visible
(読み書き)

Controls the display of a layer. This has the same effect as checking the check box next to the layer in the table of contents in ArcMap. If set to True, the layer will draw; if set to False, the layer will not be drawn. Not all layers support the visible property (for example, restricted Web service layers), so it is good practice to test for this ahead of time using the supports method.

Boolean
workspacePath
(読み取り専用)

Returns a path to the layer's workspace or connection file. Not all layers support the workspacePath property (for example, Web services), so it is good practice to test for this ahead of time using the supports method.

String

メソッドの概要

メソッド説明
findAndReplaceWorkspacePath (find_workspace_path, replace_workspace_path, {validate})

Finds and replaces a layer's workspace path with a new workspace path.

getExtent ({symbolized_extent})

Returns a layer's geometric or symbolized extent.

getSelectedExtent ({symbolized_extent})

Returns a layer's geometric or symbolized extent for selected features.

replaceDataSource (workspace_path, workspace_type, dataset_name, {validate})

Replaces a data source for a layer in a map document (.mxd) or layer (.lyr) file. It also provides the ability to switch workspace types (e.g., replaces a file geodatabase data source with an SDE data source).

save ()

Saves a layer (.lyr) file.

saveACopy (file_name, {version})

Saves a layer (.lyr) file to a different file name and, optionally, a previous version.

supports (layer_property)

Not all layers support the same set of properties. The supports property can be used to test which properties a layer does support.

メソッド

findAndReplaceWorkspacePath (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 parameter 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 replace.

String
validate

If set to True, the 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 the workspace to match the replace_workspace_path, regardless of a valid match. In this case, if a match does not exist, then the layer's data source 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.

getExtent ({symbolized_extent})
パラメータ説明データ タイプ
symbolized_extent

A value of True will return the layer's symbolized extent; otherwise, it will return the geometric extent. The symbolized extent takes into account the area the symbology covers so that it does not get cut off by the data frame's boundary.

(デフォルト値は True)

Boolean
リターン
データ タイプ説明
Extent

The getExtent method will honor a layer's definition query so if a subset of features are queried, getExtent will return the extent for only those features.

A symbolized extent takes into account the area of the feature's symbol when building the extent rectangle. Returning a symbolized extent may be best for cartographic results because symbols won't be cut off at the data frame's edges. A geometric extent may be best for analysis.

getSelectedExtent ({symbolized_extent})
パラメータ説明データ タイプ
symbolized_extent

A value of True will return the layer's symbolized extent; otherwise, it will return the geometric extent. The symbolized extent takes into account the area the symbology covers so that it does not get cut off by the data frame's boundary.

(デフォルト値は True)

Boolean
リターン
データ タイプ説明
Extent

A symbolized extent takes into account the area of the feature's symbol when building the extent rectangle. Returning a symbolized extent may be best for cartographic results because symbols won't be cut off at the data frame's edges. A geometric extent may be best for analysis.

replaceDataSource (workspace_path, workspace_type, dataset_name, {validate})
パラメータ説明データ タイプ
workspace_path

A string that includes the workspace path to the new data or connection file.

String
workspace_type

A string keyword that represents the workspace type of the new data.

  • ACCESS_WORKSPACE A personal geodatabase or Access workspace
  • ARCINFO_WORKSPACE An ArcInfo coverage workspace
  • CAD_WORKSPACEA CAD file workspace
  • EXCEL_WORKSPACEAn Excel file workspace
  • FILEGDB_WORKSPACEA file geodatabase workspace
  • NONEUsed to skip the parameter
  • OLEDB_WORKSPACEAn OLE database workspace
  • PCCOVERAGE_WORKSPACEA PC ARC/INFO Coverage workspace
  • RASTER_WORKSPACEA raster workspace
  • SDE_WORKSPACEAn SDE geodatabase workspace
  • SHAPEFILE_WORKSPACEA shapefile workspace
  • TEXT_WORKSPACEA text file workspace
  • TIN_WORKSPACEA TIN workspace
  • VPF_WORKSPACEA VPF workspace
String
dataset_name

A string that represents the name of the dataset the way it appears in the new workspace (not the name of the layer in the TOC).

String
validate

If set to True, a workspace will only be updated if the 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 the source to match the workspace_path, regardless of a valid match. In this case, if a match does not exist, then the data source 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 ()

There is a subtle difference between a layer (.lyr) file and a map layer (a layer in a map document). The save method only works when a variable references a layer file and will not work with a map layer. When a layer is loaded from a layer file it will remember the file name and use that when the save method is called. If a map layer is being referenced, a file name is not initially set, so you will need to use the saveACopy method instead.

saveACopy (file_name, {version})
パラメータ説明データ タイプ
file_name

A string that includes the location and name of the output layer (.lyr) file.

String
version

A string that sets the output version number. If a value is not used, the current version is used.

  • 10.0Version 10.0
  • 8.3Version 8.3
  • 9.0Version 9.0/9.1
  • 9.2Version 9.2
  • 9.3Version 9.3

(デフォルト値は 10.0)

String

Provides an option to save a layer (.lyr) file to a different file name and, optionally, a previous version. Features that are not supported in prior versions of the software will be removed from the newly saved layer.

supports (layer_property)
パラメータ説明データ タイプ
layer_property

The name of a particular layer property that will be tested.

  • BRIGHTNESSA raster layer's brightness value
  • CONTRASTA raster layer's contrast value
  • DATASETNAMEA layers dataset name the way it appears in the workspace
  • DATASOURCEA layer's file path or connection file
  • DEFINITIONQUERYA layer's definition query string
  • DESCRIPTIONA layer's description string
  • LABELCLASSESA layer's list of label classes
  • LONGNAMEA layer's path including the group layer(s) it may be nested within
  • NAMEA layer's name
  • SERVICEPROPERTIESConnection information for SDE and web service layers
  • SHOWLABELSA Boolean indicating if a layer's lables are toggled on or off
  • TRANSPARENCYA layer's transparency value
  • VISIBLEA Boolean indicating if a layer is toggled on or off in the TOC
  • WORKSPACEPATHA layer's workspace or connection file path

(デフォルト値は name)

String
リターン
データ タイプ説明
Boolean

There are numerous types of layers and not all of them support the same properties. For example, a feature layer supports a definition query whereas a raster layer does not, but a raster catalog does. Rather than creating individual layer objects for all possible layer types and property combinations, a support method was created to help identify which layer types support which properties. The support method gives you the option of testing the property before trying to get or set its value on a layer type that doesn't support it. The supports property will return a true if a layer supports that property.

コードのサンプル

Layer example 1:

The following script will reference a layer (.lyr) file, find all layers called Highways, turns on labels, and save the results to a new layer file.

import arcpy
lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Streets.lyr")
for lyr in arcpy.mapping.ListLayers(lyrFile):
    if lyr.name.lower() == "highways":
        lyr.showLabels = True
        lyr.saveACopy(r"C:\Project\Data\StreetsWithLabels.lyr")
del lyrFile

#Or with one less line using a wild card:

import arcpy
lyrFile = arcpy.mapping.Layer(r"C:\Project\Data\Streets.lyr")
for lyr in arcpy.mapping.ListLayers(lyrFile, "Highways"):
    lyr.showLabels = True
    lyr.saveACopy(r"C:\Project\Data\StreetsWithLabels.lyr")
del lyrFile
        
Layer example 2:

The following script will allow secured layers to render correctly by creating an SDE connection in memory before opening a map document that requires password information. This script simply defines the connection information and then exports the map document to a PDF file. It is good practice to delete this reference from memory before the script closes.

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

   
Layer example 3:

The following script will print the name of each SDE or web service layer along with the appropriate service information. Similar to the example above, since some SDE layers may be secured with password information, a temporary SDE connection file is created. This example does not print information about non-SDE or web service layers.

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

#Report service properties for layers in a map that support SERVICEPROPERTIES
mxd = arcpy.mapping.MapDocument(r"C:\Project\ServerData.mxd")
for lyr in arcpy.mapping.ListLayers(mxd):
    if lyr.supports("SERVICEPROPERTIES"):
        servProp = lyr.serviceProperties
        print "Layer name:" + lyr.name
        print "-----------------------------------------------------"
        if lyr.serviceProperties["ServiceType"] != "SDE":
            print "Service Type: " + servProp.get('ServiceType', 'N/A')
            print "    URL:         " + servProp.get('URL', 'N/A')
            print "    Connection:  " + servProp.get('Connection', 'N/A')
            print "    Server:      " + servProp.get('Server', 'N/A')
            print "    Cache:       " + str(servProp.get('Cache', 'N/A'))
            print "    User Name:   " + servProp.get('UserName', 'N/A')
            print "    Password:    " + servProp.get('Password', 'N/A')
            print ""
        else:
            print "Service Type: " + servProp.get('ServiceType', 'N/A')
            print "    Database:       " + servProp.get('Database', 'N/A')
            print "    Server:         " + servProp.get('Server', 'N/A')
            print "    Service:        " + servProp.get('Instance', 'N/A')
            print "    Version:        " + servProp.get('Version', 'N/A')
            print "    User name:      " + servProp.get('UserName', 'N/A')
            print "    Authentication: " + servProp.get('AuthenticationMode', 'N/A')
            print ""       
del mxd

7/10/2012