Resumen
Provides access to basic layer properties and methods.
Debate
Layers can be referenced from within a project using the listLayers method on the Map class or in a layer file (.lyr or .lyrx) stored on disk using the listLayers method on the LayerFile class.
The Layer object has a single, generic design to work with all layers. 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 the possible layer types and property combinations, there are some useful properties that allow you to obtain information about a layer and its supported properties. There are many is properties that allow you to determine if a layer fits into a general category, for example, is3DLayer, isFeatureLayer, isGroupLayer, isRasterLayer, isWebLayer, and so on.
There are a few specialized layers and datasets that don't fall into one of these general categories: annotation subclasses, dimension features, 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. The supports method is available to help identify which specific layer supports which specific layer property. It gives you the ability to test whether the layer supports a property before trying to get or set its value, reducing the need for additional error trapping. For example, see the following code:if lyr.supports("BRIGHTNESS"):
lyr.brightness = 10
The listLayers method on the Map class returns index values that are generated from top to bottom as they appear in the table of contents or as they appear in a layer file. The same applies if a group layer is within another group layer. For example, a map 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 longName property. 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 longName value of Group1\Layer1. If the name value is equal to the longName value, the layer is not inside a group layer. When working with the sublayers of composite layers, the longName property will contain both the sublayer and top-level layer name.
ArcGIS Pro can read legacy .lyr file types, but it can only save to .lyrx file types. If a .lyr file type is being referenced and the save method is called, it will be converted to a .lyrx file type but with the same file name.
A feature layer can support zero to many definition queries, but only one definition query can be active. It is also possible that one or many definition queries are present but none are active. There are a couple of ways to manage definition queries. First, you can use the definitionQuery property. If you set a unique SQL string on a layer that does not have a definition query or a layer that has multiple definition queries, the new definition query is added and it becomes the active query. If you set a SQL string on a layer that already has that same query, it sets that as the active definition query, if it is not already active. The second way to manage definition queries is to use the listDefinitionQueries and updateDefinitionQueries functions in combination. The listDefinitionQueries function returns a list of Python dictionaries that represent the properties associated with each query. The dictionary keys are name, sql, and isActive. Definition queries can be added, modified, or removed from the Python list using core Python. The dictionary isActive value can be set to True to set the active query. Again, only one query can be active. If you try setting more than one query to be active, an error will be returned. After changes are made, the updateDefinitionQueries function is used to set the new changes.
Changing a layer's data source is a common requirement. There is a method and a property on the Layer object that help with this. For a more detailed discussion, parameter information, scenarios, and code samples, refer to the Updating and fixing data sources help topic.
Propiedades
Propiedad | Explicación | Tipo de datos |
brightness (Lectura y escritura) | A layer's brightness value. The default, normal brightness, is 0 percent. Enter any value between +100 percent and -100 percent. Type a plus or minus sign to the left of the value to specify whether it is above or below 0. | Integer |
connectionProperties (Sólo lectura) | Returns a layer's data source connection information as a Python dictionary. | Dictionary |
contrast (Lectura y escritura) | A layer's contrast value. The default, neutral contrast, is 0 percent. Enter any value between +100 percent and -100 percent. Type a plus or minus sign to the left of the value to specify whether it is above or below 0. | Integer |
dataSource (Sólo lectura) | Returns the complete path for the layer's data source. It includes the full workspace path and name of the dataset. For enterprise geodatabase layers, a string containing the layer's connection information is returned. Sugerencia:Enterprise geodatabase layers in an ArcGIS Pro project do not retain the path to the database connection file (.sde) that was used to create the layer. | String |
definitionQuery (Lectura y escritura) | A layer's definition query. If you set a unique SQL string on a layer that does not have a definition query or a layer that has multiple definition queries, the new definition query is added and it becomes the active query. If you set a SQL string on a layer that already has that same query, it simply sets that as the active definition query, if it is not already active. | String |
is3DLayer (Sólo lectura) | Returns True if a layer is a 3D layer. | Boolean |
isBasemapLayer (Sólo lectura) | Returns True if a layer is a basemap layer. | Boolean |
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. | Boolean |
isNetworkDatasetLayer (Sólo lectura) | Returns True if a layer is an ArcGIS Network Analyst extension network dataset layer. | Boolean |
isRasterLayer (Sólo lectura) | Returns True if a layer is a raster layer. | Boolean |
isSceneLayer (Sólo lectura) | Returns True if a layer is a scene layer. | Boolean |
isTimeEnabled (Sólo lectura) | Indicates whether time is enabled on the layer. If isTimeEnabled returns True, the time property on the layer can be used to return a LayerTime object. Use the enableTime method to enable time on a layer that contains time information. | Boolean |
isWebLayer (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. Esri basemaps are an example. | Boolean |
longName (Sólo lectura) | A layer's full name including group layer and composite layer structure. | String |
maxThreshold (Lectura y escritura) | A layer's maximum scale threshold for 2D maps and its maximum distance above ground for 3D maps. A layer will not display when zoomed in beyond the maximum scale. To clear the maximum scale, set the value to 0. | Double |
metadata (Lectura y escritura) | Get or set the layer's Metadata class information. Nota:Setting metadata is dependent on the isReadOnly property value. | Metadata |
minThreshold (Lectura y escritura) | A layer's minimum scale threshold for 2D maps and its maximum distance above ground for 3D maps. A layer will not display when zoomed out beyond the minimum scale. To clear the minimum scale, set the value to 0. | Double |
name (Lectura y escritura) | The name of a layer the way it would appear in the table of contents. Spaces can be included. It is important that all layers in a map have a unique name so they can be easily referenced by their names. | String |
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. | Boolean |
symbology (Lectura y escritura) | Provides access to a layer's symbology. | Object |
time (Sólo lectura) | Returns a LayerTime object if time is enabled on the layer. | LayerTime |
transparency (Lectura y escritura) | A layer's transparency value. This enables you to see through a layer. Use values between 0 and 100. A value of 0 is not transparent. A transparency value of more than 90 percent usually results in the layer not being drawn at all. | Integer |
URI (Sólo lectura) | The Universal Resource Indicator for a layer. It is a unique identifier for a layer in a project and is sometimes required when using Python CIM access. Once a layer is added and the URI is established, the value does not change over time. For example, if you modify the layer's name, the URI will not change. | String |
visible (Lectura y escritura) | Controls the display of a layer. If set to True, the layer will draw; if set to False, the layer will not be drawn. | Boolean |
Descripción general del método
Método | Explicación |
enableTime ({startTimeField}, {endTimeField}, {autoCalculateTimeRange}, {timeDimension}) | Enables time on a layer if it has time information. |
extrusion ({extrusion_type}, {expression}) | Extrudes 2D features in a layer to display 3D symbology. |
getDefinition (cim_version) | Gets a layer's CIM definition. |
getSelectionSet () | Returns a layer's selection as a Python set of object IDs. |
listDefinitionQueries ({wildcard}) | Returns a Python list of definition queries associated with a layer. |
listLabelClasses ({wildcard}) |
Returns a Python list of LabelClass objects in a layer. |
listLayers ({wildcard}) | Returns a Python list of Layer objects from a group layer or composite layer. |
listTables ({wildcard}) | Returns a Python list of Table objects that exist within a group layer. |
saveACopy (file_name) | Saves a layer to a layer file (.lyrx). |
setDefinition (definition_object) | Sets a layer's CIM definition. |
setSelectionSet ({oidList}, {method}) | Sets a layer's selection using a Python list of Object IDs. |
supports (layer_property) | Used to determine if a particular layer type supports a property on the layer object. Not all layers support the same set of properties; the supports property can be used to test if a layer supports that property before attempting to set it. |
updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case}) | Replaces connection properties using a dictionary or a path to a workspace. |
updateDefinitionQueries (definitionQueries) | Updates a layer's collection of definition queries. |
updateLayerFromJSON (json_data) | Updates a Layer from a JSON string. |
Métodos
enableTime ({startTimeField}, {endTimeField}, {autoCalculateTimeRange}, {timeDimension})
Parámetro | Explicación | Tipo de datos |
startTimeField | The name of the field containing the start time values. If each feature has a single time field, specify that field name in the startTimeField and leave endTimeField blank. If each feature has a start and end time field, specify both the startTimeField and endTimeField. (El valor predeterminado es None) | String |
endTimeField | The name of the field containing the end time values. Not all layers use an end time field. If each feature has a single time field, specify that field name in the startTimeField and leave endTimeField blank. If each feature has a start and end time field, specify both the startTimeField and endTimeField. (El valor predeterminado es None) | String |
autoCalculateTimeRange | If set to True, the start and end time attribute information is used to calculate the layer's time extent. (El valor predeterminado es True) | Boolean |
timeDimension | The name of the dimension containing time values when using netCDF data. (El valor predeterminado es None) | String |
All parameters on the enableTime method are optional. If startTimeField and endTimeField are not specified, the method will evaluate the data and attempt to come up with appropriate default values.
After running the enableTime method, the time property on the layer can be used to return a LayerTime object. If a MapFrame on a Layout contains time-enabled layers, the MapTime class can be used to access map time settings.
extrusion ({extrusion_type}, {expression})
Parámetro | Explicación | Tipo de datos |
extrusion_type | A string that specifies the extrusion method. The default value is NONE which turns off layer extrusion.
(El valor predeterminado es NONE) | String |
expression | A string that defines the extrusion expression, which provides an absolute extrusion height for each feature. (El valor predeterminado es None) | String |
Extrusion is the process of vertically stretching a flat 2D shape to create a 3D object. This provides a method to create three-dimensional symbology from two-dimensional features. Polygon and line features have all five extrusion_type options available; point features don't use MAX_HEIGHT or MIN_HEIGHT options.
getDefinition (cim_version)
Parámetro | Explicación | Tipo de datos |
cim_version | A string that represents the major version of the CIM. | String |
CIM-level access to additional object properties was introduced at version 2.4. Esri follows the semantic versioning specification. This means that until the next major release—for example, 3.0—when breaking API changes are allowed, the value to be used with cim_version is V2. Once 3.0 is released, a new V3 option will become available. This gives Python script authors control over the CIM version that will be used during execution if there is a possibility that breaking changes may be introduced in the new version.
For more information about working with the CIM and samples, see Python CIM Access.
getSelectionSet ()
Provides an easy way to retrieve the layer's current selection.
listDefinitionQueries ({wildcard})
Parámetro | Explicación | Tipo de datos |
wildcard | A wildcard is based on the query name and is not case sensitive. A combination of asterisks (*) and characters can be used to limit the resulting list. (El valor predeterminado es None) | String |
Tipo de datos | Explicación |
List | A Python list of dictionaries that represent the properties associated with each query. The dictionary keys are name, sql, and isActive. |
Definition queries can be added, modified, or removed from the Python list using standard practices. The dictionary isActive value can be set to True to set the active query. Again, only one query can be active. If you try setting more than one query to be active, an error will be returned. After changes are made, the updateDefinitionQueries function is used to set the new changes.
listLabelClasses ({wildcard})
Parámetro | Explicación | Tipo de datos |
wildcard | A wildcard is based on the label class name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list. (El valor predeterminado es None) | String |
Tipo de datos | Explicación |
List | Returns a Python list of LabelClass objects in a layer. |
Returns a Python list of LabelClass objects in a layer.
listLayers ({wildcard})
Parámetro | Explicación | Tipo de datos |
wildcard | A wildcard is based on the layer name and is not case sensitive. A combination of asterisks (*) and characters can be used to help limit the resulting list. (El valor predeterminado es None) | String |
Tipo de datos | Explicación |
List | Returns a Python list of Layer objects from a group layer or composite layer. |
Returns a Python list of Layer objects from a group layer or composite layer.
listTables ({wildcard})
Parámetro | Explicación | Tipo de datos |
wildcard | A wildcard is based on the table name and is not case sensitive. A combination of asterisks (*) and characters can be used to limit the resulting list. (El valor predeterminado es None) | String |
Tipo de datos | Explicación |
List | A Python list of Table objects in a layer. |
Returns a Python list of Table objects that exist within a group layer. ListTables always returns a list object even if only one table is returned.
It is possible that there may be tables in a group layer with the same name. If this is the case, other properties may need to be used to isolate a specific layer. Properties such as a tables's datasource or definitionQuery or URI can be used to do this. It is ideal that all tables be uniquely named.
saveACopy (file_name)
Parámetro | Explicación | Tipo de datos |
file_name | A string that includes the location and name of the output layer file (.lyrx). | String |
If a group layer is being saved, all of the layers below it in the TOC will also be saved to the layer file (.lyrx).
setDefinition (definition_object)
Parámetro | Explicación | Tipo de datos |
definition_object | A modified CIM definition object originally retrieved using getDefinition. | Object |
For more information about working with the CIM and samples, see Python CIM access.
setSelectionSet ({oidList}, {method})
Parámetro | Explicación | Tipo de datos |
oidList [oidList,...] | A Python list of Object IDs to use along with the appropriate selection method. (El valor predeterminado es None) | Integer |
method | A string that specifies which selection method to use.
(El valor predeterminado es NEW) | String |
This method provides an easy way to manage a layer's selection. To clear the selection, use the NEW selection method with an empty list or don't set any parameters.
Note: Python Lists are used for setting the oidList but Python 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 |
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 supports 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.
Boolean properties don't need to be tested using supports because if a layer property isn't supported for that layer type, a False value gets returned.
updateConnectionProperties (current_connection_info, new_connection_info, {auto_update_joins_and_relates}, {validate}, {ignore_case})
Parámetro | Explicación | Tipo de datos |
current_connection_info | A string that represents the workspace path or a Python dictionary that contains connection properties to the source you want to update. | String |
new_connection_info | A string that represents the workspace path or a Python dictionary that contains connection properties with the new source information. | String |
auto_update_joins_and_relates | If set to True, the updateConnectionProperties method will also update the connections for associated joins or relates. (El valor predeterminado es True) | Boolean |
validate | If set to True, the connection properties will only be updated if the new_connection_info value is a valid connection. If it is not valid, the connection will not be replaced. If set to False, the method will set all connections to match the new_connection_info, regardless of a valid match. In this case, if a match does not exist, then the data sources would be broken. (El valor predeterminado es True) | Boolean |
ignore_case | Determines whether searches will be case sensitive or not. By default, queries are case sensitive. To perform case-insensitive queries, set ignore_case to True. (El valor predeterminado es False) | Boolean |
For more detailed discussion, parameter information, scenarios, and code samples, refer to the Updating and fixing data sources help topic.
updateDefinitionQueries (definitionQueries)
Parámetro | Explicación | Tipo de datos |
definitionQueries [definitionQueries,...] | Updates a list of dictionaries that represent the properties of each definition query. | List |
This function is typically used to apply the changes that have been made to the results returned by the listDefinitionQueries function.
updateLayerFromJSON (json_data)
Parámetro | Explicación | Tipo de datos |
json_data | The layer definition in JavaScript Object Notation (JSON) format. See the ExportWebMap JSON specification for more information. ArcGIS API for JavaScript and ArcGIS Web AppBuilder allow you to get this JSON string from the web app. The layer definition is a subset of the webmap_json used in the ConvertWebMapToArcGISProject 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 web tool that uses the ConvertWebMapToArcGISProject function in web map printing applications that support changing the renderer (or other properties) of dynamic web service layers. If your web tool replaces the service layers with staged vector layers after running ConvertWebMapToArcGISProject, updateLayerFromJSON will apply the renderer (or other layer properties) as specified in the webmap_json to the corresponding vector layers staged in the layout template. For more information and a code sample, see ConvertWebMapToArcGISProject.
Muestra de código
The following script prints the name of each map in a project and lists the names of the layers in each map. The script also appends a (BROKEN) prefix to the layer name if it has a broken data source.
import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Projects\YosemiteNP\Yosemite.aprx")
for m in aprx.listMaps():
print("Map: {0} Layers".format(m.name))
for lyr in m.listLayers():
if lyr.isBroken:
print("(BROKEN) " + lyr.name)
else:
print(" " + lyr.name)
del aprx
The following script clears all layer definition queries and turns off labels for all layers in a map named Yosemite National Park:
import arcpy
aprx = arcpy.mp.ArcGISProject(r"C:\Projects\YosemiteNP\Yosemite.aprx")
m = aprx.listMaps("Yosemite National Park")[0]
for lyr in m.listLayers():
if lyr.supports("DEFINITIONQUERY"):
lyr.definitionQuery = ""
if lyr.supports("SHOWLABELS"):
lyr.showLabels = False
aprx.save()
del aprx
The following script adds a new definition query to a layer or sets the same query to be the active definition query if the SQL string already exists:
p = arcpy.mp.ArcGISProject('current')
m = p.listMaps()[0]
l = m.listLayers()[0]
if l.supports('DefinitionQuery'):
l.definitionQuery = "AREA > 3000000"
The following script creates a new definition query by appending a Python dictionary to the existing list queries. Because a query may already be active, it is important to first clear existing active queries before setting the new active query.
p = arcpy.mp.ArcGISProject('current')
m = p.listMaps()[0]
l = m.listLayers()[0]
if l.supports('DefinitionQuery'):
#Get the list of definition queries
dql = l.listDefinitionQueries()
#Clear active definition queries otherwise the update will fail if there is already an active query
for dq in dql:
dq['isActive'] = False
#Create a new definition query and append it to the list
dql.append({'name': 'Appended Query', 'sql': "name = 'Lake Superior'", 'isActive': True})
#Update the definition queries with the newly modified list
l.updateDefinitionQueries(dql)