Resumen
Provides access to layer properties and methods. It can either reference layers in a map document (.mxd) or layers in a layer (.lyr) file.
Debate
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 the ArcMap Layer Properties dialog box and it also provides methods for saving layer files. The Layer function, the ListLayers function and the listLegendItemLayers method on the Legend object all provide ways to reference a Layer object.
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 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 (for example, display properties, field aliases, selection symbology, and so on). The UpdateLayer function allows you to replace all layer properties available in the ArcMap Layer Properties dialog box using a layer (.lyr) file that contains the customizations.
Group layers and other sublayers (for example, 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 value 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 file that is also persisted in memory. If this function is executed 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 a layer file on disk will place a lock on the (.lyr) file. It is good practice to remove the object reference using the Python del command at the end of a script or within a Python 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 a more detailed discussion, parameter information, scenarios, and code samples, please refer to the Updating and fixing data sources with arcpy.mapping help topic.
Depending on the symbology type, a layer's symbology can be modified. There are a limited number of supported symbology types for which properties and methods are available. It is good practice to first test the layer's symbologyType property. If a value of OTHER is returned, then the layer's symbology can't be modified. If the value returned is not OTHER, then the layer's symbology property will return one of the following symbology classes, each with their own unique set of methods and properties: GraduatedColorsSymbology, GraduatedSymbolsSymbology, RasterClassifiedSymbology, and UniqueValuesSymbology.
Time-management operations can be performed for time-enabled layers. Not all layer types support time properties. Therefore, it is good practice to first test if the layer supports time using the supports method. If the layer does support time, then time properties can be accessed from the LayerTime class.
Sintaxis
Layer (lyr_file_path)
Parámetro | Explicación | Tipo de datos |
lyr_file_path | A string that includes the full path and file name of an existing layer (.lyr) file. | String |
Propiedades
Propiedad | Explicación | Tipo de datos |
brightness (Lectura y escritura) | 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 and feature layers), so it is good practice to test for this ahead of time using the supports method. | Integer |
contrast (Lectura y escritura) | 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 and fabric layers), so it is good practice to test for this ahead of time using the supports method. | Integer |
credits (Lectura y escritura) | Provides the ability to either get or set the layer's credits or copyright information. | String |
datasetName (Sólo lectura) | 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 (Sólo lectura) | 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 and web services), so it is good practice to test for this ahead of time using the supports method. | String |
definitionQuery (Lectura y escritura) | Provides the ability to get or set a layer's definition query. Not all layers support the definitionQuery property (for example, raster layers and group layers), so it is good practice to test for this ahead of time using the supports method. | String |
description (Lectura y escritura) | 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 |
isBroken (Sólo lectura) | Returns True if a layer's data source is broken. | Boolean |
isFeatureLayer (Sólo lectura) | Returns True if a layer is a feature layer. | Boolean |
isGroupLayer (Sólo lectura) | Returns True if a layer is a group layer. | Boolean |
isNetworkAnalystLayer (Sólo lectura) | Returns True if a layer is an ArcGIS Network Analyst extension layer type. | Boolean |
isRasterizingLayer (Sólo lectura) | 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 (Sólo lectura) | Returns True if a layer is a raster layer. | Boolean |
isServiceLayer (Sólo lectura) | Returns True if a layer is a GIS service layer. GIS services are automated geographic information services that are published and accessed over the web using standard technologies and protocols. | Boolean |
labelClasses (Lectura y escritura) | Provides access to a layer's label class properties by returning a list of LabelClass objects. Individual LabelClass object properties can be read and modified and written back to the layer. Not all layers support the labelClasses property (for example, raster layers and annotation layers), so it is good practice to test for this ahead of time using the supports method. | LabelClass |
longName (Sólo lectura) | 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 |
maxScale (Lectura y escritura) | Provides the ability to set or get the layer's maximum scale threshold. | Double |
minScale (Lectura y escritura) | Provides the ability to set or get the layer's minimum scale threshold. | Double |
name (Lectura y escritura) | 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 (Sólo lectura) | 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
Keys for a web service dictionary
| Dictionary |
showLabels (Lectura y escritura) | 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 and 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 |
symbology (Sólo lectura) | Returns a reference to the layer's symbology class. Each supported layer symbology class has its own unique set of properties. It is best to first determine the layer's symbologyType before attempting to modify the symbology class properties. | Object |
symbologyType (Sólo lectura) | Returns a string that represents the layer's symbology class type. Not all layer symbology class types are supported; for those that are not, the keyword OTHER is returned. The following is a list of possible values:
| Object |
time (Sólo lectura) | Returns the LayerTime class that provides access to time properties of time-enabled layers. | Object |
transparency (Lectura y escritura) | 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 percent usually results in the layer not being drawn at all. Not all layers support the transparency property (for example, fabric group layers and web service sublayers), so it is good practice to test for this ahead of time using the supports method. | Integer |
visible (Lectura y escritura) | 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 (Sólo lectura) | 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 |
Descripción general de los métodos
Método | Explicación |
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. |
getSelectionSet () | Returns a layer's selection as a Python set of object IDs. |
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. |
setSelectionSet (method, oidList) | Sets a layer's selection using a Python set of object IDs. |
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. |
updateLayerFromJSON (json_layer_definition) | Updates a Layer from a JSON string. |
Métodos
findAndReplaceWorkspacePath (find_workspace_path, replace_workspace_path, {validate})
Parámetro | Explicación | Tipo de datos |
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. (El valor predeterminado es 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})
Parámetro | Explicación | Tipo de datos |
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. (El valor predeterminado es True) | Boolean |
Valor de retorno
Tipo de datos | Explicación |
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})
Parámetro | Explicación | Tipo de datos |
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. (El valor predeterminado es True) | Boolean |
Valor de retorno
Tipo de datos | Explicación |
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.
getSelectionSet ()
Provides an easy way to retrieve the layer's current selection.
replaceDataSource (workspace_path, workspace_type, {dataset_name}, {validate})
Parámetro | Explicación | Tipo de datos |
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.
| 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). If dataset_name is not provided, the replaceDataSource method will attempt to replace the dataset by finding a table with a the same name as the layer's current dataset property. | 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. (El valor predeterminado es 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})
Parámetro | Explicación | Tipo de datos |
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. The default value will use the current version.
(El valor predeterminado es None) | 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.
setSelectionSet (method, oidList)
Parámetro | Explicación | Tipo de datos |
method | A string that specifies which selection method to use.
(El valor predeterminado es None) | String |
oidList [oidList,...] | A Python set of object IDs to use along with the appropriate selection method. | List |
This method provides an easy way to manage a layer's selection. To clear the selection, use the NEW selection method with an empty set. Python Sets or Lists can be used for the oidList but sets get returned from the getSelectionSet method on the Layer object.
supports (layer_property)
Parámetro | Explicación | Tipo de datos |
layer_property | The name of a particular layer property that will be tested.
(El valor predeterminado es name) | String |
Valor de retorno
Tipo de datos | Explicación |
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.
updateLayerFromJSON (json_layer_definition)
Parámetro | Explicación | Tipo de datos |
json_layer_definition | The layer definition in JavaScript Object Notation (JSON) format. See the ExportWebMap JSON specification for more information. The ArcGIS Web APIs (JavaScript, Flex, and Silverlight) allow developers to easily get this JSON string from a web application. The layer definition is a subset of the webmap_json used in the ConvertWebMapToMapDocument function. You don't need to create the web map JSON; the APIs take care of it for you. However, you need to extract the layer definition from the full webmap_json. | String |
This function is intended to be used in a geoprocessing service that uses the ConvertWebMapToMapDocumentfunction in web map printing applications that support changing the renderer (or other properties) of dynamic web service layers. If your geoprocessing services replaces the service layers with staged vector layers after running ConvertWebMapToMapDocument, updateLayerFromJSON will apply the renderer (or other layer properties) as specified in the webmap_json to the corresponding vector layers staged in the template map document. For more information and a code sample, see ConvertWebMapToMapDocument.
Ejemplo de código
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, 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('Service', '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
Layer example 4
The following script modifies the symbology for a layer in a map document. It first updates the layer's symbology using a layer file on disk with the UpdateLayer function. The layer file contains a custom color ramp that is applied to the layer. Next, it verifies that the layer has graduated color symbology. Finally, the script modifies a number of the properties on the GraduatedColors symbology class and exports the result to PDF.
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Census")[0]
lyr = arcpy.mapping.ListLayers(mxd, "StatePopulation", df)[0]
lyrFile = arcpy.mapping.Layer(r"C:\Project\LYRs\Population.lyr")
arcpy.mapping.UpdateLayer(df, lyr, lyrFile, True)
if lyr.symbologyType == "GRADUATED_COLORS":
lyr.symbology.valueField = "POP2000"
lyr.symbology.numClasses = 4
lyr.symbology.classBreakValues = [250000, 999999, 4999999, 9999999, 35000000]
lyr.symbology.classBreakLabels = ["250,000 to 999,999", "1,000,000 to 4,999,999",
"5,000,000 to 9,999,999", "10,000,000 to 35,000,000"]
arcpy.mapping.ExportToPDF(mxd, r"C:\Project\Output\StatePopulation.pdf")
del mxd, lyrFile
Layer example 5
The following script tests if a layer file supports time and if time properties have been set. It then uses time information (start time and end time) to calculate the time extent of a time-enabled layer.
import arcpy, datetime
lyr = arcpy.mapping.Layer(r'C:\Project\Data\Time\TemperatureWithTime.lyr')
if lyr.supports("TIME"):
lyrTime = lyr.time
if lyr.time.isTimeEnabled:
startTime = lyrTime.startTime
endTime = lyrTime.endTime
timeDelta = endTime - startTime
print "Start Time: " + str(startTime)
print "End Time: " + str(endTime)
print "Time Extent: " + str(timeDelta)
else:
print "No time properties have been set on the layer"
else:
print "Time is not supported on this layer"