The arcgis.layers module provides components for visualizing GIS data and analysis. This module also includes mapping layers like MapImageLayer, SceneLayer and VectorTileLayer.
Service
- class arcgis.layers._service_factory.Service(url_or_item: Item | str = None, server=None, initialize=False, parent_url=None)
Bases:
objectThe Service class allows users to pass a url string or an
Item, along with an optionalGISconnection or specificServerobject to return an instance of the specific ArcGIS API for Python object the service represents.Parameter
Description
url_or_item
Required String. Internet endpoint for the service to initialize as a Python object.
server
- Returns:
An object representing the service type of the input value.
Example: Initialize a FeatureLayerCollection directly from an Item
from arcgis.gis import GIS from arcgis.layers import Service gis = GIS(profile="your_online_profile") flyr_item = gis.content.get("<item_id>") flc = Service( url_or_item=flyr_item, server=gis ) flc
Output:
<FeatureLayerCollection url:"https://services7.arcgis.com/<org_id>/arcgis/rest/services/ancient_places/FeatureServer">
Example #2: Initialize a FeatureLayer from a url
from arcgis.gis import GIS from arcgis.layers import Service gis = GIS(profile="your_organization_profile") flyr_url = https://services7.arcgis.com/<org_id>/arcgis/rest/services/ca_public_schools/FeatureServer/0 flyr_obj = Service( url_or_item=flyr_url ) print(f"Feature Layer object: {flyr_obj}") print(f"Type of object: {type(flyr_obj)}")
Output:
Feature Layer object: <FeatureLayer url:"https://services7.arcgis.com/<org_id>/arcgis/rest/services/ca_public_schools/FeatureServer/0"> Type of object: <class 'arcgis.features.layer.FeatureLayer'>
BasemapServices
- class arcgis.layers.BasemapServices(gis=None)
Bases:
objectDeprecated since version 2.4.2: Removed in: 2.5.0. Use basemap_styles_service property found in BasemapManager class in the arcgis.map package.
The basemap styles service is a ready-to-use location service that serves vector and image tiles that represent geographic features around the world. It includes styles that represent topographic features, road networks, footpaths, building footprints, water features, administrative boundaries, and satellite imagery. The styles are returned as JSON based on the Mapbox Style Specification or the ArcGIS Web Map Specification. The service also supports displaying localized language place labels, places, and worldviews. Custom basemap styles can also be created from the the default styles.
When you are using a rendered Map instance, you can specify the basemap service to the basemap property to apply the style to the map.
- property languages
Returns a list of supported languages for the basemap styles. To see which languages are supported by each service look at the documentation found here: https://developers.arcgis.com/rest/basemap-styles/
- property places
Returns a list of supported places for the basemap styles. To see which services support which places look at the documentation found here: https://developers.arcgis.com/rest/basemap-styles/
- property worldviews
Returns a list of supported worldviews for the basemap styles. To see which services support which worldviews look at the documentation found here: https://developers.arcgis.com/rest/basemap-styles/
BasemapService
- class arcgis.layers.BasemapService(service_name: str, service_path: str, gis)
Bases:
objectDeprecated since version 2.4.2: Removed in: 2.5.0. Use basemap_styles_service property found in BasemapManager class in the arcgis.map package.
Represents a basemap style service that is available for use in the basemap styles service.
- property style: dict
Returns the style JSON for the specified style name or path.
Working with 3D Maps
SceneLayer
- class arcgis.layers.SceneLayer(url, gis=None, parent_url=None)
Bases:
LayerThe
SceneLayerclass represents a Web scene layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features.
Note
Web scene layers can be used to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.PointCloudLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
SceneLayerManager
- class arcgis.layers.SceneLayerManager(url: str, gis=None, scene_lyr=None)
Bases:
_GISResourceThe
SceneLayerManagerclass allows administration (if access permits) of ArcGIS Online hosted scene layers. ASceneLayerManageroffers access to map and layer content.- cancel_job(job_id: str) dict | None
The
cancel_joboperation supports cancelling a job while update tiles is running from a hosted feature service. The result of this operation is a response indicating success or failure with error code and description.Parameter
Description
job_id
Required String. The job id to cancel.
- edit(item: str | Item) dict | None
The
editmethod edits from anItemobject.Parameter
Description
item
Required ItemId or
Itemobject. The TPK file’s item id. This TPK file contains to-be-extracted bundle files which are then merged into an existing cache service.- Returns:
A dictionary
- import_package(item: str | Item) dict | None
The
importmethod imports from anItemobject.Parameter
Description
item
Required ItemId or
Itemobject. The TPK file’s item id. This TPK file contains to-be-extracted bundle files which are then merged into an existing cache service.- Returns:
A dictionary
- jobs() dict | None
The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.
- rebuild_cache(layers: int | list[int]) dict | None
The rebuild_cache operation update the scene layer cache to reflect any changes made to the feature layer used to publish this scene layer. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.
Parameter
Description
layers
Required int or list of int. Comma separated values indicating the id of the layers to rebuild in the cache.
Ex: [0,1,2]
- refresh() dict | None
The
refreshoperation refreshes a service, which clears the web server cache for the service.
- rerun_job(job_id: str, code: str) dict | None
The
rerun_joboperation supports re-running a canceled job from a hosted map service. The result of this operation is a response indicating success or failure with error code and description.Parameter
Description
code
Required string, parameter used to re-run a given jobs with a specific error code:
ALL | ERROR | CANCELEDjob_id
Required string, job to reprocess
- Returns:
A boolean or dictionary
- swap(target_service_name: str) dict | None
The swap operation replaces the current service cache with an existing one.
Note
The
swapoperation is for ArcGIS Online only.Parameter
Description
target_service_name
Required string. Name of service you want to swap with.
- Returns:
dictionary indicating success or error
- update() dict | None
The
updatemethod starts update generation for ArcGIS Online. It updates the underlying source dataset for the service, essentially refreshing the underlying package data.- Returns:
Dictionary.
- update_attribute(layers: int | list[int]) dict | None
Update atrribute is a “light rebuild” where attributes of the layers selected are updated and can be used for change tracking. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.
Parameter
Description
layers
Required int or list of int. Comma separated values indicating the id of the layers to update in the cache.
Ex: [0,1,2]
- update_cache(layers: int | list[int]) dict | None
Update Cache is a “light rebuild” where attributes and geometries of the layers selected are updated and can be used for change tracking on the feature layer to only update nodes with dirty tiles. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.
Parameter
Description
layers
Required int or list of int. Comma separated values indicating the id of the layers to update in the cache.
Ex: [0,1,2]
EnterpriseSceneLayerManager
- class arcgis.layers.EnterpriseSceneLayerManager(url: str, gis=None, scene_lyr=None)
Bases:
_GISResourceThe
EnterpriseSceneLayerManagerclass allows administration (if access permits) of ArcGIS Enterprise hosted scene layers. ASceneLayeroffers access to layer content.Note
Url must be admin url such as:
https://services.myserver.com/arcgis/rest/admin/services/serviceName/SceneServer/- change_provider(provider: str)
Allows for the switching of the service provide and how it is hosted on the ArcGIS Server instance.
Values:
‘ArcObjects’ means the service is running under the ArcMap runtime i.e. published from ArcMap
‘ArcObjects11’: means the service is running under the ArcGIS Pro runtime i.e. published from ArcGIS Pro
‘DMaps’: means the service is running in the shared instance pool (and thus running under the ArcGIS Pro provider runtime)
- Returns:
Boolean
- edit(service_dictionary: dict)
To edit a service, you need to submit the complete JSON representation of the service, which includes the updates to the service properties. Editing a service causes the service to be restarted with updated properties.
- Returns:
boolean
- rebuild_cache(layer: list[int] | None = None, extent: dict | None = None, area_of_interest: dict | None = None) str
The rebuild_cache operation update the scene layer cache to reflect any changes made to the feature layer used to publish this scene layer. The results of the operation is the url to the scene service once it is done rebuilding.
Parameter
Description
layer
Optional list of integers. The list of layers to cook.
extent
Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.
area_of_interest
Optional dict representing a feature. Specify the updated area of interest.
- Syntax:
- {
“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: False
}
- Returns:
If successful, the url to the scene service
- update_attribute(layer: list[int] | None = None, extent: dict | None = None, area_of_interest: dict | None = None) str
Update attribute is a “light rebuild” where attributes of the layers selected are updated and can be used for change tracking. The results of the operation is the url to the scene service once it is done updating.
Parameter
Description
layer
Optional list of integers. The list of layers to cook.
extent
Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.
area_of_interest
Optional dict representing a feature. Specify the updated area of interest.
- Syntax:
- {
“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: false
}
- Returns:
If successful, the url to the scene service
- update_cache(layer: list[int] | None = None, extent: dict | None = None, area_of_interest: dict | None = None) str
Update Cache is a “light rebuild” where attributes and geometries of the layers selected are updated and can be used for change tracking on the feature layer to only update nodes with dirty tiles,. The results of the operation is the url to the scene service once it is done updating.
Parameter
Description
layer
Optional list of integers. The list of layers to cook.
extent
Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.
area_of_interest
Optional dict representing a feature. Specify the updated area of interest.
- Syntax:
- {
“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: False
}
- Returns:
If successful, the url to the scene service
BuildingLayer
- class arcgis.layers.BuildingLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
BuildingLayerclass represents a Web building layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.BuildingLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
IntegratedMeshLayer
- class arcgis.layers.IntegratedMeshLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
IntegratedMeshLayerclass represents a Web scene Integrated Mesh layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
Tiles3DLayer
- class arcgis.layers.Tiles3DLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
Tiles3DLayerclass represents a Web scene 3D Tile Service Layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /3DTilesServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.
Object3DLayer
- class arcgis.layers.Object3DLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
Object3DLayerrepresents a Web scene 3D Object layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
Point3DLayer
- class arcgis.layers.Point3DLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
Point3DLayerclass represents a Web scene 3D Point layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
PointCloudLayer
- class arcgis.layers.PointCloudLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
PointCloudLayerclass represents a Web scene Point Cloud layer.Note
Point Cloud layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.PointCloudLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
VoxelLayer
- class arcgis.layers.VoxelLayer(url: str, gis=None, parent_url=None)
Bases:
LayerThe
VoxelLayerclass represents a Web Scene Voxel layer.Note
Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the
SceneLayerclass for more information.Parameter
Description
url
Required string, specify the url ending in
/SceneServer/gis
Optional
GISobject. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.layers import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.layers.VoxelLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
- property manager: SceneLayerManager | EnterpriseSceneLayerManager
The
managerproperty returns an instance ofSceneLayerManagerclass orEnterpriseSceneLayerManagerclass which provides methods and properties for administering this service.
Working with Map Service Layers
MapServiceLayer
- class arcgis.layers.MapServiceLayer(url: str, gis: GIS | None = None, container: MapImageLayer | None = None, dynamic_layer: dict | None = None)
Bases:
LayerCreates the appropriate Python object for a map service layer or table.
MapServiceLayeris a factory, not a fixed concrete layer type. During construction it reads metadata from a resource URL ending in/MapServer/<layer-or-table-id>. Depending on the resource’s RESTtype, it returns aMapFeatureLayer,MapRasterLayer,MapTable, or a genericLayerfor an unrecognized type such as a group layer.Map services published by ArcGIS Server can expose dynamic drawing and layer or table queries. Map services hosted by ArcGIS Online or Portal can be cache-only and may not expose those operations. Inspect the service and resource
capabilitiesandadvancedQueryCapabilitiesproperties before using an operation. Dynamic layer definitions additionally require the map service’ssupportsDynamicLayersproperty to beTrue.Example: Examining properties of MapServiceLayer output
from arcgis.gis import GIS from arcgis.layers import MapServiceLayer map_service_lyr_url = 'https://example.dn.com/server/rest/services/<folder>/<svc_name>/MapServer/0' map_flyr = MapServiceLayer(url=map_service_lyr_url, gis=gis) map_flyr.properties.advancedQueryCapabilities
Output:
- {
“supportsStatistics”: true, “supportsSqlExpression”: true, “supportsQueryWithResultType”: true, “supportsTrueCurve”: true, “supportsOrderBy”: true, “supportsQueryRelatedPagination”: true, “supportsSqlFormat”: false, “useStandardizedQueries”: true, “supportsLod”: false, “supportsQueryWithDistance”: true, “supportsQueryWithCacheHint”: false, “supportsQueryWithDatumTransformation”: true, “supportsCountDistinct”: true, “supportsCurrentUserQueries”: true, “supportsAdvancedQueryRelated”: true, “supportsReturningQueryExtent”: true, “supportsQueryWithLodSR”: false, “supportsPagination”: true, “supportsMaxRecordCountFactor”: false, “supportsDistinct”: true, “supportsTimeRelation”: true, “supportsQueryAnalytic”: false, “supportsPercentileStatistics”: true, “supportsHavingClause”: true
}
Parameter
Description
url
Required string. The URL of a layer or table resource, ending in
/MapServer/<layer-or-table-id>. UseMapImageLayerfor the root/MapServerURL.gis
Optional
GIS. The GIS used to read the resource metadata and access the service. If omitted, the active GIS is used or an anonymous GIS is created.container
Optional
MapImageLayer. The map image layer that contains the resource.dynamic_layer
Optional dictionary. A dynamic layer or table definition accepted by supported ArcGIS Server map services.
- Returns:
A
MapFeatureLayer,MapRasterLayer,MapTable, orLayer, according to the resource metadata.
Example:
from arcgis.layers import MapFeatureLayer, MapServiceLayer layer = MapServiceLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/" "Census/MapServer/3" ) isinstance(layer, MapFeatureLayer)
Output:
True
MapFeatureLayer
- class arcgis.layers.MapFeatureLayer(url: str, gis: GIS | None = None, container: MapImageLayer | None = None, dynamic_layer: dict | None = None, time_filter: datetime | str | list[datetime | str | None] | tuple[datetime | str | None, ...] | None = None)
Bases:
LayerRepresents a feature sublayer in a map service.
A
MapFeatureLayerprovides access to the features and operations of a sublayer in aMapImageLayer. Instances can be created from a layer URL or obtained from thelayersproperty of aMapImageLayer.Parameter
Description
url
Required string. The URL of the map service sublayer. The URL typically ends with
/MapServer/<layer-id>.gis
Optional
GIS. The GIS to which the layer belongs. A GIS is required to access secured layers. If not provided, the active GIS is used; otherwise, an anonymous GIS is created.container
Optional
MapImageLayer. The map image layer that contains this sublayer.dynamic_layer
Optional dictionary. The dynamic layer definition to include in supported requests.
time_filter
Optional
datetime.datetime, string, list, or tuple. The time instant or two-value extent used to filter the layer. String values represent Unix epoch times in milliseconds.- attachements
Deprecated since version 2.4.1: Use the attachments property instead.
Deprecated since version 2.4.1: Use the attachments property instead.
- property attachments: AttachmentManager | None
Provides access to the attachments associated with the layer’s features.
- Returns:
An
AttachmentManagerwhen the layer supports querying attachments; otherwise,None.
- property container: MapImageLayer
Returns the map image layer that contains this sublayer.
- Returns:
The containing
MapImageLayer.
- export_attachments(output_folder: str, label_field: str | None = None) None
Exports layer attachments in an ImageNet-style folder structure.
Attachments are written below an
imagesdirectory. Amapping.txtfile maps each feature object ID to its exported image paths. Whenlabel_fieldis provided, its values are used to group images into subdirectories.Parameter
Description
output_folder
Required string. An existing folder in which to create the exported attachment structure.
label_field
Optional string. A field whose values identify the category subdirectory for each feature. If not provided, attachments are stored in the default image directory.
- Returns:
None
- classmethod fromitem(item: Item, layer_id: int = 0) MapFeatureLayer
Creates a map feature layer from a map service item.
Parameter
Description
item
Required
Item. An item whose type isMap Service.layer_id
Optional integer. The zero-based position of the sublayer in the map service’s
layerscollection. The default is0.- Returns:
The selected
MapFeatureLayer.
Example:
from arcgis.layers import MapFeatureLayer from arcgis.gis import GIS gis = GIS("home") map_service_item = gis.content.get("<map-service-item-id>") map_feature_layer = MapFeatureLayer.fromitem( item=map_service_item, layer_id=2, )
- generate_renderer(definition: dict[str, Any], where: str | None = None) dict[str, Any]
Generates a renderer from a classification definition.
Use
baseSymbolandcolorRampin the definition to control the symbols assigned to each class. An optional SQL where clause limits the features used to generate the renderer.Note
When the operation is performed on a table, the result contains data classes without symbols.
Parameter
Description
definition
Required dictionary. A class breaks or unique value classification definition used to generate the renderer. See Generate Renderer.
where
Optional string. A where clause for which the data needs to be classified. Any legal SQL where clause operating on the fields in the dynamic layer/table is allowed.
- Returns:
A dictionary containing the generated renderer definition.
- get_html_popup(oid: str) dict | str
Returns the HTML pop-up authored for a feature.
Parameter
Description
oid
Required string. The object ID of the feature whose pop-up will be returned.
- Returns:
A dictionary containing the pop-up response. An empty string is returned when HTML pop-ups are not configured for the layer.
- get_unique_values(attribute: str, query_string: str = '1=1') list
Returns the unique values for a field.
Parameter
Description
attribute
Required string. The field to query.
query_string
Optional string. An SQL where clause used to filter features before values are returned. The default is
1=1.- Returns:
A list of unique field values, preserving the service response order.
Example:
from arcgis.layers import MapFeatureLayer from arcgis.gis import GIS # connect to your GIS and get the map feature layer item gis = GIS("home") map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") map_feature_layer = MapFeatureLayer.fromitem(item=map_image_item, layer_id=2) # call get unique values method fo the 'Name' attribute unique_values = map_feature_layer.get_unique_values( attribute="Name", query_string="name_2 LIKE '%K%'", ) isinstance(unique_values, list)
Output:
True
- query(where: str = '1=1', text: str | None = None, out_fields: str | list[str] = '*', time_filter: list[int | datetime | None] | str | None = None, geometry_filter: GeometryFilter | None = None, return_geometry: bool = True, return_count_only: bool = False, return_ids_only: bool = False, return_distinct_values: bool = False, return_extent_only: bool = False, group_by_fields_for_statistics: str | None = None, statistic_filter: StatisticFilter | None = None, result_offset: int | None = None, result_record_count: int | None = None, object_ids: str | None = None, distance: int | None = None, units: str | None = None, max_allowable_offset: float | None = None, out_sr: int | None = None, geometry_precision: int | None = None, gdb_version: str | None = None, order_by_fields: list[str] | str | None = None, out_statistics: list[dict[str, Any]] | None = None, return_z: bool = False, return_m: bool = False, multipatch_option=None, quantization_parameters: dict[str, Any] | None = None, return_centroid: bool = False, return_all_records: bool = True, result_type: str | None = None, historic_moment: int | datetime | None = None, sql_format: str | None = None, return_true_curves: bool = False, return_exceeded_limit_features: bool | None = None, as_df: bool = False, datum_transformation: int | dict[str, Any] | None = None, range_values: dict[str, Any] | None = None, parameter_values: dict[str, Any] | None = None, **kwargs) FeatureSet | int | dict | DataFrame
Queries the map feature layer using an SQL statement and optional spatial, temporal, or statistical filters.
Parameter
Description
where
Optional string. The SQL where clause. The default is
1=1.text
Optional string. A literal search text. If the layer has a display field associated with it, the server searches for this text in this field.
out_fields
Optional list of field names to return. Field names can be specified as a list or a comma-separated string. The default is “*”, which returns all the fields.
object_ids
Optional string. The object IDs of this layer or table to be queried. The object ID values should be a comma-separated string.
distance
Optional integer. The buffer distance for the input geometries. The distance unit is specified by units. For example, if the distance is 100, the query geometry is a point, units is set to meters, and all points within 100 meters of the point are returned.
units
Optional string. The unit for calculating the buffer distance. If unit is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. This parameter only applies if supportsQueryWithDistance is true.
- Value options:
esriSRUnit_Meter|esriSRUnit_StatuteMile|esriSRUnit_Foot|esriSRUnit_Kilometer|esriSRUnit_NauticalMile|esriSRUnit_USNauticalMile
time_filter
Optional list containing start and end times as
datetime.datetimeobjects or Unix epoch values in milliseconds. UseNonefor an open start or end.from datetime import datetime time_filter = [datetime(2024, 1, 1), None]
geometry_filter
Optional
filterobject. Allows for the information to be filtered on spatial relationship with another geometry.max_allowable_offset
Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation in the units of out_sr. If out_sr is not specified, the value is in units of the spatial reference of the layer.
out_sr
Optional Integer. The WKID for the spatial reference of the returned geometry.
geometry_precision
Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. This applies to X and Y values only (not m or z-values).
gdb_version
Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If not specified, the query will apply to the published map’s version.
return_geometry
Optional boolean. If true, geometry is returned with the query. Default is true.
return_distinct_values
Optional boolean. If True, it returns distinct values based on fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true.
return_ids_only
Optional boolean. Default is False. If True, the response only includes an array of object IDs. Otherwise, the response is a
FeatureSet.return_count_only
Optional boolean. If True, the response only includes the count of features/records satisfying the query. Otherwise, the response is a
FeatureSet. The default is False. This option supersedes thereturn_ids_onlyparameter. Ifreturn_count_only=True, the response returns both the count and the extent.return_extent_only
Optional boolean. If True, the response only includes the extent of the features satisfying the query. If returnCountOnly=true, the response will return both the count and the extent. The default is False. This parameter applies only if the supportsReturningQueryExtent property of the layer is true.
order_by_fields
Optional string or list of strings. One or more field names by which to order the results. Use
ASCorDESCfor ascending or descending, respectively, following every field to be ordered:order_by_fields = "STATE_NAME ASC, RACE DESC, GENDER ASC"
group_by_fields_for_statistics
Optional string. One or more field names on which to group results for calculating the statistics.
group_by_fields_for_statistics = "STATE_NAME, GENDER"
out_statistics
Optional List. The definitions for one or more field-based statistics to be calculated.
- Syntax:
out_statistics = [ { "statisticType": "count", "onStatisticField": "Field1", "outStatisticFieldName": "Field1_Count", }, { "statisticType": "avg", "onStatisticField": "Field2", "outStatisticFieldName": "Field2_Average", }, ]
return_z
Optional boolean. If True, Z values are included in the results if the features have Z values. Otherwise, Z values are not returned. The default is False.
return_m
Optional boolean. If True, M values are included in the results if the features have M values. Otherwise, M values are not returned. The default is False.
multipatch_option
Optional x/y footprint. This option dictates how the geometry of a multipatch feature will be returned.
result_offset
Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + ith value). This option is ignored if return_all_records is True (i.e. by default). This parameter cannot be specified if the service does not support pagination.
result_record_count
Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s maxRecordCount property. This option is ignored if return_all_records is True (i.e. by default). This parameter cannot be specified if the service does not support pagination.
quantization_parameters
Optional dict. Used to project the geometry onto a virtual grid, likely representing pixels on the screen.
return_centroid
Optional boolean. Used to return the geometry centroid associated with each feature returned. If True, the result includes the geometry centroid. The default is False.
return_all_records
Optional boolean. When True, the query operation will call the service until all records that satisfy the where_clause are returned.
Note
result_offset and result_record_count will be ignored if set to True. If return_count_only, return_ids_only, or return_extent_only are True, this parameter is ignored.
result_type
Optional string. Controls the number of features returned by the operation. Options:
None|standard|tileNote
See Query (Feature Service/Layer) for full explanation.
historic_moment
Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer’s
propertiesresource. If not specified, the query will apply to the current features.sql_format
Optional string. The sql_format parameter can be either standard SQL92 or it can use the native SQL of the underlying datastore. The default is None, which means it depends on the useStandardizedQuery layer property. Values:
None|standard|nativereturn_true_curves
Optional boolean. When set to True, returns true curves in output geometries. When set to False, curves are converted to densified polylines or polygons.
return_exceeded_limit_features
Optional boolean. Optional parameter which is true by default. When set to true, features are returned even when the results include the exceededTransferLimit: True property.
When set to False and querying with resultType = tile, features are not returned when the results include exceededTransferLimit: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.
as_df
Optional boolean. If True, the results are returned as a DataFrame instead of a
FeatureSet.datum_transformation
Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Coordinate systems and transformations. For more information on datum transformations, please see the transformation parameter in the Project operation.
Example:
Inputs
Description
WKID
Integer.
datum_transformation = 4326
WKT
Dict.
datum_transformation = {"wkt": "<WKT>"}
Composite
Dict.
datum_transformation = { "geoTransforms": [ {"wkid": 108190, "forward": True}, {"wkt": "<WKT>", "forward": False}, ] }
range_values
Optional List. Allows you to filter features from the layer that are within the specified range instant or extent.
range_values = [ {"name": "elevation", "value": [1000, 1500]}, {"name": "temperature", "value": 20}, ]
Note
None is allowed in value-range case to indicate infinity
# all features with values <= 1500 range_values = [ {"name": "elevation", "value": [None, 1500]} ] # all features with values >= 1000 range_values = [ {"name": "elevation", "value": [1000, None]} ]
parameter_values
Optional Dict. Allows you to filter the layers by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.
When a parameterInfo allows multiple values, you must pass them in an array.
Note
Check parameterValues at the Query (Map Service/Layer) for details on parameterized filters.
kwargs
Optional dictionary. Additional ArcGIS REST API query parameters, specified using REST parameter names such as
cacheHint. Explicit named arguments take precedence when the same REST parameter is supplied in both places. See Query (Map Service/Layer).- Returns:
A
FeatureSetcontaining matching features. Depending on the options, the result can instead be an integer count, a dictionary, or a pandasDataFrame.
Example:
from arcgis.layers import MapImageLayer, MapFeatureLayer from arcgis.gis import GIS # connect to your GIS and get the web map item gis = GIS(url, username, password) map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") map_feature_layer = MapFeatureLayer.fromitem(item = map_image_item, layer_id = 2) query_count = map_feature_layer.query( where="STATUS = 'Open'", return_count_only=True, ) query_count
Output:
149
Queries records related to features in this layer.
The result contains feature sets grouped by source layer/table object IDs. Each
FeatureSetcontainsFeatureobjects including the values for the fields requested by the user.Note
For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include geometries.
Note
See
query()for more information about querying a map feature layer.Parameter
Description
object_ids
Required string. The object IDs of the table/layer to be queried
relationship_id
Required string. The ID of the relationship to be queried.
out_fields
Optional string or list of strings. The fields from the related table/layer to be included in the returned feature set. This list is a comma delimited list of field names. If you specify the shape field in the list of return fields, it is ignored. To request geometry, set return_geometry to true. You can also specify the wildcard “*” as the value of this parameter. In this case, the results will include all the field values.
definition_expression
Optional string. The definition expression to be applied to the related table/layer. From the list of objectIds, only those records that conform to this expression are queried for related records.
return_geometry
Optional boolean. If true, the feature set includes the geometry associated with each feature. The default is true.
max_allowable_offset
Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation. The max_allowable_offset is in the units of the outSR. If out_wkid is not specified, then max_allowable_offset is assumed to be in the unit of the spatial reference of the map.
geometry_precision
Optional integer. This option can be used to specify the number of decimal places in the response geometries.
out_wkid
Optional Integer. The spatial reference of the returned geometry.
gdb_version
Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer queried is true.
return_z
Optional boolean. If true, Z values are included in the results if the features have Z values. Otherwise, Z values are not returned. The default is false.
return_m
Optional boolean. If true, M values are included in the results if the features have M values. Otherwise, M values are not returned. The default is false.
historic_moment
Optional integer or
datetime.datetime. The historic moment to query. This parameter applies only if the supportsQueryWithHistoricMoment property of the layers being queried is set to true. This setting is provided in the layer resource.If historic_moment is not specified, the query will apply to the current features.
- Syntax:
historic_moment=<Epoch time in milliseconds>
return_true_curve
Optional boolean. The default is
False. When set to true, returns true curves in output geometries; otherwise, curves are converted to densified polylines or polygons.- Returns:
A dictionary containing related record groups keyed by source object ID.
- property renderer: dict | None
Gets or sets the renderer used to display the layer.
Note
Setting this property overrides the layer’s default symbology when it is displayed in a
Map.- Returns:
A dictionary containing the renderer definition, or
None.
- property time_filter: str | None
Gets or sets the time filter applied to the layer.
The filter can be a
datetime.datetime, a string containing a Unix epoch value in milliseconds, or a two-value list or tuple that defines a start and end time. UseNonefor an open start or end. The stored value is a comma-separated string when an extent is set.Example:
from datetime import datetime, timezone map_feature_layer.time_filter = [ datetime(2021, 1, 1, tzinfo=timezone.utc), datetime(2022, 1, 10, tzinfo=timezone.utc), ] map_feature_layer.time_filter
Output:
'1609459200000,1641772800000'
- Returns:
A string containing a time instant or comma-separated time extent, or
Nonewhen no filter is set.
MapRasterLayer
- class arcgis.layers.MapRasterLayer(url: str, gis: GIS | None = None, container: MapImageLayer | None = None, dynamic_layer: dict | None = None, time_filter: datetime | str | list[datetime | str | None] | tuple[datetime | str | None, ...] | None = None)
Bases:
MapFeatureLayerRepresents a raster sublayer in a map service.
A
MapRasterLayerprovides access to a raster layer published as part of aMapImageLayer. It represents aRaster Layerresource below aMapServerendpoint; it does not represent a standalone image service. UseImageryLayerfor anImageServerresource.Instances are normally returned by
MapServiceLayeror from thelayerscollection of aMapImageLayer. Operations inherited fromMapFeatureLayerare available only when supported by the containing map service and advertised by the layer’s properties.Parameter
Description
url
Required string. The URL of the raster sublayer, typically ending in
/MapServer/<layer-id>.gis
Optional
GIS. The GIS used to access the service. A GIS is required for secured services. If omitted, the active GIS is used or an anonymous GIS is created.container
Optional
MapImageLayer. The map image layer containing this raster sublayer.dynamic_layer
Optional dictionary. A dynamic layer definition. The containing map service must advertise
supportsDynamicLayersasTrue.time_filter
Optional datetime, string, list, or tuple. A time instant or two-value time extent used by supported requests.
MapImageLayer
- class arcgis.layers.MapImageLayer(url: str, gis: GIS | None = None)
Bases:
LayerRepresents an ArcGIS map service and its layers and tables.
A
MapImageLayercan export maps, identify and find features, retrieve legends and service information, create dynamic layers, generate KML, and export cached tiles when those capabilities are advertised by the service. Runtime service metadata determines which operations and parameters are available because support varies by ArcGIS Online and Enterprise release.Parameter
Description
url
Required string. Map service URL ending in
/MapServer.gis
Optional
GIS. The GIS used to authenticate requests. If omitted, an anonymous GIS is created.Example:
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS() layer = MapImageLayer( "https://sampleserver6.arcgisonline.com/arcgis/rest/services/" "Census/MapServer", gis, ) layer.legend
- create_dynamic_layer(layer: dict[str, Any]) FeatureLayer | None
The
create_dynamic_layermethod creates a dynamic layer. A dynamic layer / table represents a single layer / table of a map service published by ArcGIS Server or of a registered workspace. This resource is supported only when the map image layer supports dynamic layers, as indicated bysupportsDynamicLayerson the map image layer properties.Parameter
Description
layer
Required dict. Dynamic layer/table source definition.
Syntax:
{“id”: <layerOrTableId>,“source”: <layer source>, //required“definitionExpression”: “<definitionExpression>”,“drawingInfo”:{“renderer”: <renderer>,“transparency”: <transparency>,“scaleSymbols”: <true,false>,“showLabels”: <true,false>,“labelingInfo”: <labeling info>},“layerTimeOptions”: //supported only for time enabled map layers{“useTime” : <true,false>,“timeDataCumulative” : <true,false>,“timeOffset” : <timeOffset>,“timeOffsetUnits” : “<esriTimeUnitsCenturies,esriTimeUnitsDays,esriTimeUnitsDecades,esriTimeUnitsHours,esriTimeUnitsMilliseconds,esriTimeUnitsMinutes,esriTimeUnitsMonths,esriTimeUnitsSeconds,esriTimeUnitsWeeks,esriTimeUnitsYears |esriTimeUnitsUnknown>”}}- Returns:
FeatureLayeror None (if not enabled)
# USAGE EXAMPLE >>> from arcgis.layers import MapImageLayer >>> from arcgis.gis import GIS # connect to your GIS and get the web map item >>> gis = GIS(url, username, password) >>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") >>> layer_to_add ={ "id": <layerId>, "source": <layer source> "definitionExpression": "<definitionExpression>", "drawingInfo": { "renderer": <renderer>, "transparency": <transparency>, "scaleSymbols": <true>, "showLabels": <true>, "labelingInfo": <labeling info> }, "layerTimeOptions": { "useTime" : <true,false>, "timeDataCumulative" : <true>, "timeOffset" : <timeOffset>, "timeOffsetUnits" : "<esriTimeUnitsCenturies>" } } >>> new_layer = map_image_item.create_dynamic_layer(layer= layer_to_add) >>>type(new_layer) <arcgis.features.FeatureLayer>
- estimate_export_tiles_size(export_by: str, levels: str, tile_package: bool = False, export_extent: str = 'DEFAULT', area_of_interest: dict[str, Any] | Polygon | None = None, asynchronous: bool = True, **kwargs) dict
The
estimate_export_tiles_sizemethod is an asynchronous task that allows estimation of the size of the tile package or the cache data set that you download using theexport_tilesoperation. This operation can also be used to estimate the tile count in a tile package and determine if it will exceed themaxExportTileCountlimit set by the administrator of the service. The result of this operation isMapServiceJob. This job response contains reference toMap Service Resultresource that returns the total size of the cache to be exported (in bytes) and the number of tiles that will be exported.Parameter
Description
export_by
Required string. The criteria that will be used to select the tile service levels to export. The values can be Level IDs, cache scales or the Resolution (in the case of image services). Values:
“levelId” | “resolution” | “scale”
levels
Required string. Specify the tiled service levels for which you want to get the estimates. The values should correspond to Level IDs, cache scales or the Resolution as specified in export_by parameter. The values can be comma separated values or a range.
Example 1: 1,2,3,4,5,6,7,8,9 Example 2: 1-4,7-9
tile_package
Optional boolean. Allows estimating the size for either a tile package or a cache raster data set. Specify the value true for tile packages format and false for Cache Raster data set. The default value is False
export_extent
The extent (bounding box) of the tile package or the cache dataset to be exported. If extent does not include a spatial reference, the extent values are assumed to be in the spatial reference of the map. The default value is full extent of the tiled map service. Syntax: <xmin>, <ymin>, <xmax>, <ymax> Example: -104,35.6,-94.32,41
area_of_interest
Optional dictionary or Polygon. This allows exporting tiles within the specified polygon areas. This parameter supersedes extent parameter.
Example:
{ “features”: [{“geometry”:{“rings”:[[[-100,35],[-100,45],[-90,45],[-90,35],[-100,35]]],“spatialReference”:{“wkid”:4326}}}]}asynchronous
Optional boolean. The estimate function is run asynchronously requiring the tool status to be checked manually to force it to run synchronously the tool will check the status until the estimation completes. The default is True, which means the status of the job and results need to be checked manually. If the value is set to False, the function will wait until the task completes.
- Returns:
dictionary
- export_map(bbox: str, bbox_sr: int | dict[str, Any] | _geometry.SpatialReference | None = None, size: str = '600,550', dpi: int = 200, image_sr: int | dict[str, Any] | _geometry.SpatialReference | None = None, image_format: str = 'png', layer_defs: dict[str, Any] | None = None, layers: str | None = None, transparent: bool = False, time_value: list[int] | list[_dt.datetime._dt.datetime] | None = None, time_options: dict[str, Any] | None = None, dynamic_layers: dict[str, Any] | None = None, gdb_version: str | None = None, scale: float | None = None, rotation: float | None = None, transformation: list[int] | list[dict[str, Any]] | None = None, map_range_values: list[dict[str, Any]] | None = None, layer_range_values: list[dict[str, Any]] | None = None, layer_parameter: list[dict[str, Any]] | None = None, historic_moment: int | None = None, clipping: dict[str, Any] | None = None, spatial_filter: dict[str, Any] | None = None, time_relation: str | None = None, selection_definitions: list[dict[str, Any]] | None = None, f: str = 'json', save_folder: str | None = None, save_file: str | None = None, **kwargs) str
The
export_mapoperation is performed on a map service resource. The result of this operation is a map image resource. This resource provides information about the exported map image such as its URL, its width and height, extent and scale.Parameter
Description
bbox
Required string. The extent (bounding box) of the exported image. Unless the bbox_sr parameter has been specified, the bbox is assumed to be in the spatial reference of the map.
bbox_sr
Optional integer,
SpatialReference. The spatial reference of the bbox.size
Optional string. size - size of image in pixels
dpi
Optional integer. dots per inch
image_sr
Optional integer,
SpatialReference. The spatial reference of the output image.image_format
Optional string. The format of the exported image. The default format is .png. Values:
png | png8 | png24 | jpg | pdf | bmp | gif | svg | svgz | emf | ps | png32
layer_defs
Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.
layers
Optional string. Determines which layers appear on the exported map. There are four ways to specify which layers are shown:
show: Only the layers specified in this list will be exported.hide: All layers except those specified in this list will be exported.include: In addition to the layers exported by default, the layers specified in this list will be exported.exclude: The layers exported by default excluding those specified in this list will be exported.transparent
Optional boolean. If true, the image will be exported with the background color of the map set as its transparent color. The default is false.
Note
Only the .png and .gif formats support transparency.
time_value
Optional list. The time instant or the time extent of the features to be identified.
time_options
Optional dict. The time options per layer. Users can indicate whether or not the layer should use the time extent specified by the time parameter or not, whether to draw the layer features cumulatively or not and the time offsets for the layer.
dynamic_layers
Optional dict. Use dynamicLayers property to reorder layers and change the layer data source. dynamicLayers can also be used to add new layer that was not defined in the map used to create the map service. The new layer should have its source pointing to one of the registered workspaces that was defined at the time the map service was created. The order of dynamicLayers array defines the layer drawing order. The first element of the dynamicLayers is stacked on top of all other layers. When defining a dynamic layer, source is required.
gdb_version
Optional string. Switch map layers to point to an alternate geodatabase version.
scale
Optional float. Use this parameter to export a map image at a specific map scale, with the map centered around the center of the specified bounding box (bbox)
rotation
Optional float. Use this parameter to export a map image rotated at a specific angle, with the map centered around the center of the specified bounding box (bbox). It could be positive or negative number.
transformations
Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different than the map service’s spatial reference. It is an array of transformation elements.
map_range_values
Optional list. Allows you to filter features in the exported map from all layer that are within the specified range instant or extent.
layer_range_values
Optional dictionary. Allows you to filter features for each individual layer that are within the specified range instant or extent. Note: Check range infos at the layer resources for the available ranges.
layer_parameter
Optional list. Allows you to filter the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.
- Returns:
A string, image of the map.
# USAGE EXAMPLE >>> from arcgis.layers import MapImageLayer >>> from arcgis.gis import GIS # connect to your GIS and get the web map item >>> gis = GIS(url, username, password) >>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") >>> map_image_item.export_map(bbox="-104,35.6,-94.32,41", bbox_sr = 4326, image_format ="png", layers = "include", transparent = True, scale = 40.0, rotation = -45.0 )
- export_tiles(levels: str, export_by: str = 'LevelID', tile_package: bool = True, export_extent: dict[str, Any] | str | None = None, optimize_for_size: bool = True, compression: int = 75, area_of_interest: dict[str, Any] | Polygon | None = None, asynchronous: bool = False, storage_format: str | None = None, **kwargs) str | dict
The
export_Tilesoperation is performed as an asynchronous task and allows client applications to download map tiles from a server for offline use. This operation is performed on aMap Servicethat allows clients to export cache tiles. The result of this operation is aMap Service Job. This job response contains a reference to theMap Service Resultresource, which returns a URL to the resulting tile package (.tpk) or a cache raster dataset.export_Tilescan be enabled in a service by using ArcGIS Desktop or the ArcGIS Server Administrator Directory. In ArcGIS Desktop make an admin or publisher connection to the server, go to service properties, and enableAllow ClientstoExport Cache Tilesin the advanced caching page of theService Editor. You can also specify the maximum tiles clients will be allowed to download.Note
The default maximum allowed tile count is 100,000. To enable this capability using the Administrator Directory, edit the service, and set the properties
exportTilesAllowed=TrueandmaxExportTilesCount= 100000.Note
In ArcGIS Server 10.2.2 and later versions, exportTiles is supported as an operation of the Map Server. The use of the
http://Map_Service/exportTiles/submitJoboperation is deprecated. You can provide arguments to the exportTiles operation as defined in the following parameters table:Parameter
Description
levels
Required string. Specifies the tiled service levels to export. The values should correspond to Level IDs, cache scales. or the resolution as specified in export_by parameter. The values can be comma separated values or a range. Make sure tiles are present at the levels where you attempt to export tiles. Example 1: 1,2,3,4,5,6,7,8,9 Example 2: 1-4,7-9
export_by
Required string. The criteria that will be used to select the tile service levels to export. The values can be Level IDs, cache scales. or the resolution. The default is ‘LevelID’. Values:
levelId | resolution | scale
tile_package
Optional boolean. Allows exporting either a tile package or a cache raster data set. If the value is true, output will be in tile package format, and if the value is false, a cache raster data set is returned. The default value is True.
export_extent
Optional dictionary or string. The extent (bounding box) of the tile package or the cache dataset to be exported. If extent does not include a spatial reference, the extent values are assumed to be in the spatial reference of the map. The default value is full extent of the tiled map service. Syntax:
<xmin>, <ymin>, <xmax>, <ymax>
Example 1: -104,35.6,-94.32,41 Example 2:
{“xmin” : -109.55, “ymin” : 25.76,“xmax” : -86.39, “ymax” : 49.94,“spatialReference” : {“wkid” : 4326}}optimize_for_size
Optional boolean. Use this parameter to enable compression of JPEG tiles and reduce the size of the downloaded tile package or the cache raster data set. Compressing tiles slightly compromises the quality of tiles but helps reduce the size of the download. Try sample compressions to determine the optimal compression before using this feature. The default value is True.
compression=75,
Optional integer. When optimize_for_size=true, you can specify a compression factor. The value must be between 0 and 100. The value cannot be greater than the default compression already set on the original tile. For example, if the default value is 75, the value of compressionQuality must be between 0 and 75. A value greater than 75 in this example will attempt to up sample an already compressed tile and will further degrade the quality of tiles.
area_of_interest
Optional dictionary, Polygon. The area_of_interest polygon allows exporting tiles within the specified polygon areas. This parameter supersedes the exportExtent parameter.
Example:
{ “features”: [{“geometry”:{“rings”:[[[-100,35],[-100,45],[-90,45],[-90,35],[-100,35]]],“spatialReference”:{“wkid”:4326}}}]}asynchronous
Optional boolean. Default False, this value ensures the returns are returned to the user instead of the user having the check the job status manually.
storage_format
Optional string. Specifies the type of tile package that will be created.
tpk- Tiles are stored using Compact storage format. It is supported across the ArcGIS platform.tpkx- Tiles are stored using CompactV2 storage format, which provides better performance on network shares and cloud store directories. This improved and simplified package structure type is supported by newer versions of ArcGIS products such as ArcGIS Online 7.1, ArcGIS Enterprise 10.7, and ArcGIS Runtime 100.5. This is the default.- Returns:
A path to download file is asynchronous is
False. IfTrue, a dictionary is returned.
- find(search_text: str, layers: str, contains: bool = True, search_fields: str | None = None, sr: dict[str, Any] | str | SpatialReference | None = None, layer_defs: dict[str, Any] | None = None, return_geometry: bool = True, max_offset: int | None = None, precision: int | None = None, dynamic_layers: dict[str, Any] | None = None, return_z: bool = False, return_m: bool = False, gdb_version: str | None = None, return_unformatted: bool = False, return_field_name: bool = False, transformations: list[int] | list[dict[str, Any]] | None = None, map_range_values: list[dict[str, Any]] | None = None, layer_range_values: dict[str, Any] | None = None, layer_parameters: list[dict[str, Any]] | None = None, **kwargs) dict
The
findmethod performs the map servicefindoperation.Parameter
Description
search_text
Required string.The search string. This is the text that is searched across the layers and fields the user specifies.
layers
Optional string. The layers to perform the identify operation on. There are three ways to specify which layers to identify on:
top: Only the top-most layer at the specified location.
visible: All visible layers at the specified location.
all: All layers at the specified location.
contains
Optional boolean. If false, the operation searches for an exact match of the search_text string. An exact match is case sensitive. Otherwise, it searches for a value that contains the search_text provided. This search is not case sensitive. The default is true.
search_fields
Optional string. List of field names to look in.
sr
Optional dict, string, or SpatialReference. The well-known ID of the spatial reference of the input and output geometries as well as the map_extent. If sr is not specified, the geometry and the map_extent are assumed to be in the spatial reference of the map, and the output geometries are also in the spatial reference of the map.
layer_defs
Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.
return_geometry
Optional boolean. If true, the result set will include the geometries associated with each result. The default is true.
max_offset
Optional integer. This option can be used to specify the maximum allowable offset to be used for generalizing geometries returned by the identify operation.
precision
Optional integer. This option can be used to specify the number of decimal places in the response geometries returned by the identify operation. This applies to X and Y values only (not m or z-values).
dynamic_layers
Optional dict. Use dynamicLayers property to reorder layers and change the layer data source. dynamicLayers can also be used to add new layer that was not defined in the map used to create the map service. The new layer should have its source pointing to one of the registered workspaces that was defined at the time the map service was created. The order of dynamicLayers array defines the layer drawing order. The first element of the dynamicLayers is stacked on top of all other layers. When defining a dynamic layer, source is required.
return_z
Optional boolean. If true, Z values will be included in the results if the features have Z values. Otherwise, Z values are not returned. The default is false.
return_m
Optional boolean.If true, M values will be included in the results if the features have M values. Otherwise, M values are not returned. The default is false.
gdb_version
Optional string. Switch map layers to point to an alternate geodatabase version.
return_unformatted
Optional boolean. If true, the values in the result will not be formatted i.e. numbers will be returned as is and dates will be returned as epoch values.
return_field_name
Optional boolean. If true, field names will be returned instead of field aliases.
transformations
Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different from the map service’s spatial reference. It is an array of transformation elements.
map_range_values
Optional list. Allows you to filter features in the exported map from all layer that are within the specified range instant or extent.
layer_range_values
Optional dictionary. Allows you to filter features for each individual layer that are within the specified range instant or extent. Note: Check range infos at the layer resources for the available ranges.
layer_parameters
Optional list. Allows you to filter the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.
- Returns:
A dictionary
# USAGE EXAMPLE >>> from arcgis.layers import MapImageLayer >>> from arcgis.gis import GIS # connect to your GIS and get the web map item >>> gis = GIS(url, username, password) >>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") >>> search_results = map_image_item.find(search_text = "Hurricane Data", contains = True, layers = "top", return_geometry = False, max_offset = 100, return_z = True, return_m = False, ) >>> type(search_results) <Dictionary>
- classmethod fromitem(item: Item) MapImageLayer
The
fromitemmethod returns the layer at the specified index from a layerItemobject.Parameter
Description
item
Required Item. An item containing layers.
index
Optional int. The index of the layer amongst the item’s layers
- Returns:
The layer at the specified index.
# Usage Example >>> layer.fromitem(item="9311d21a9a2047d19c0faaebd6f2cca6", index=3)
- generate_kml(save_location: str, name: str, layers: str, options: str = 'composite') dict | bytes | str
The
generate_Kmloperation is performed on a map service resource. The result of this operation is a KML document wrapped in a KMZ file.Note
The document contains a network link to the KML Service endpoint with properties and parameters you specify.
Parameter
Description
save_location
Required string. Save folder.
name
Required string. The name of the resulting KML document. This is the name that appears in the Places panel of Google Earth.
layers
Required string. the layers to perform the generateKML operation on. The layers are specified as a comma-separated list of layer ids.
options
Required string. The layer drawing options. Based on the option chosen, the layers are drawn as one composite image, as separate images, or as vectors. When the KML capability is enabled, the ArcGIS Server administrator has the option of setting the layer operations allowed. If vectors are not allowed, then the caller will not be able to get vectors. Instead, the caller receives a single composite image. values: composite, separateImage, nonComposite
- Returns:
A string to the file path
- get_legend(dynamic_layers: list[dict[str, Any]] | None = None, dpi: int | None = None, size: str | None = None) dict
Returns the service legend with optional dynamic-layer patch settings.
dynamic_layersrequires dynamic-layer support.dpiandsizerequire ArcGIS Server 10.6.1 or later.
- identify(geometry: Geometry | list, map_extent: str, image_display: str | None = None, geometry_type: str = 'Point', sr: dict[str, Any] | str | SpatialReference = None, layer_defs: dict[str, Any] | None = None, time_value: list[str] | str | None = None, time_options: dict | None = None, layers: str = 'all', tolerance: int | None = None, return_geometry: bool = True, max_offset: int | None = None, precision: int = 4, dynamic_layers: dict[str, Any] | None = None, return_z: bool = False, return_m: bool = False, gdb_version: str | None = None, return_unformatted: bool = False, return_field_name: bool = False, transformations: list[dict] | list[int] | None = None, map_range_values: list[dict[str, Any]] | None = None, layer_range_values: dict[str, Any] | None = None, layer_parameters: list[dict[str, Any]] | None = None, historic_moment: int | None = None, clipping: dict[str, Any] | None = None, spatial_filter: dict[str, Any] | None = None, time_relation: str | None = None, **kwargs) dict
The
identifyoperation is performed on a map service resource to discover features at a geographic location. The result of this operation is an identify results resource.Note
Each identified result includes its
name,layer ID,layer name,geometry,geometry type, and other attributes of that result as name-value pairs.Parameter
Description
geometry
Required
Geometryor list. The geometry to identify on. The type of the geometry is specified by the geometryType parameter. The structure of the geometries is same as the structure of the JSON geometry objects returned by the API (See Geometry Objects). In addition to the JSON structures, for points and envelopes, you can specify the geometries with a simpler comma-separated syntax.geometry_type
Required string.The type of geometry specified by the geometry parameter. The geometry type could be a point, line, polygon, or an envelope. Values:
“Point” | “Multipoint” | “Polyline” | “Polygon” | “Envelope”
map_extent
Required string. The extent or bounding box of the map currently being viewed.
sr
Optional dict, string, or SpatialReference. The well-known ID of the spatial reference of the input and output geometries as well as the map_extent. If sr is not specified, the geometry and the map_extent are assumed to be in the spatial reference of the map, and the output geometries are also in the spatial reference of the map.
layer_defs
Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.
time_value
Optional list. The time instant or the time extent of the features to be identified.
time_options
Optional dict. The time options per layer. Users can indicate whether or not the layer should use the time extent specified by the time parameter or not, whether to draw the layer features cumulatively or not and the time offsets for the layer.
layers
Optional string. The layers to perform the identify operation on. There are three ways to specify which layers to identify on:
top: Only the top-most layer at the specified location.visible: All visible layers at the specified location.all: All layers at the specified location.
tolerance
Optional integer. The distance in screen pixels from the specified geometry within which the
identifyoperation should be performed. The value for the tolerance is an integer.image_display
Optional string. The screen image display parameters (width, height, and DPI) of the map being currently viewed. The mapExtent and the image_display parameters are used by the server to determine the layers visible in the current extent. They are also used to calculate the distance on the map to search based on the tolerance in screen pixels.
Syntax:
<width>, <height>, <dpi>
return_geometry
Optional boolean. If true, the result set will include the geometries associated with each result. The default is true.
max_offset
Optional integer. This option can be used to specify the maximum allowable offset to be used for generalizing geometries returned by the identify operation.
precision
Optional integer. This option can be used to specify the number of decimal places in the response geometries returned by the identify operation. This applies to X and Y values only (not m or z-values).
dynamic_layers
Optional dict. Use dynamicLayers property to reorder layers and change the layer data source. dynamicLayers can also be used to add new layer that was not defined in the map used to create the map service. The new layer should have its source pointing to one of the registered workspaces that was defined at the time the map service was created. The order of dynamicLayers array defines the layer drawing order. The first element of the dynamicLayers is stacked on top of all other layers. When defining a dynamic layer, source is required.
return_z
Optional boolean. If true, Z values will be included in the results if the features have Z values. Otherwise, Z values are not returned. The default is false.
return_m
Optional boolean.If true, M values will be included in the results if the features have M values. Otherwise, M values are not returned. The default is false.
gdb_version
Optional string. Switch map layers to point to an alternate geodatabase version.
return_unformatted
Optional boolean. If true, the values in the result will not be formatted i.e. numbers will be returned as is and dates will be returned as epoch values. The default is False.
return_field_name
Optional boolean. Default is False. If true, field names will be returned instead of field aliases.
transformations
Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different than the map service’s spatial reference. It is an array of transformation elements. Transformations specified here are used to project features from layers within a map service to sr.
map_range_values
Optional list of dictionary(ies). Allows for the filtering features in the exported map from all layer that are within the specified range instant or extent.
layer_range_values
Optional Dictionary. Allows for the filtering of features for each individual layer that are within the specified range instant or extent.
layer_parameters
Optional list of dictionary(ies). Allows for the filtering of the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.
- Returns:
A dictionary
# USAGE EXAMPLE from arcgis.layers import MapImageLayer from arcgis.gis import GIS # connect to your GIS and get the web map item gis = GIS(url, username, password) map_image_item = gis.content.get("2aaddab96684405880d27f5261125061") identified = map_image_item.identify(geometry = geom1, geometry_type = "Multipoint", image_display = "width", return_geometry =True, return_z = True, return_m = True, return_field_name = True, )
- property item_info: dict
Retrieves the service’s item information.
The item information card contains descriptive details published with the service, including its title, summary, description, tags, extent, access information, and licensing information. Available keys depend on the service and the ArcGIS Server version.
- Returns:
A dictionary containing the service’s item information.
- property kml: dict
The
kmlmethod retrieves the KML file for the layer.- Returns:
A KML file
- property legend: dict
The
legendproperty represents a map service’s legend. It returns the legend information for all layers in the service. Each layer’s legend information includes the symbol images and labels for each symbol. Each symbol is an image of size 20 x 20 pixels at 96 DPI. Additional information for each layer such as the layer ID, name, and min and max scales are also included.Note
The legend symbols include the base64 encoded imageData as well as a url that could be used to retrieve the image from the server.
- Returns:
Dictionary of legend information
- property manager: MapImageLayerManager | EnterpriseMapImageLayerManager
The
managerproperty returns an instance ofMapImageLayerManagerclass for ArcGIS Online andEnterpriseMapImageLayerManagerclass for ArcGIS Enterprise which provides methods and properties for administering this service.
- property metadata: str
The
metadataproperty retrieves the service’s XML metadata file- Returns:
An XML metadata file
- query_legends(bbox: str | None = None, bbox_sr: int | dict[str, Any] | None = None, layers: str | None = None, layer_defs: dict[str, Any] | None = None, size: str | None = None, image_sr: int | dict[str, Any] | None = None, historic_moment: int | None = None, dpi: int | None = None, time_value: str | list[int] | None = None, time_relation: str | None = None, time_options: dict[str, Any] | None = None, dynamic_layers: list[dict[str, Any]] | None = None, gdb_version: str | None = None, scale: float | None = None, rotation: float | None = None, transformation: list[int] | list[dict[str, Any]] | None = None, layer_parameters: list[dict[str, Any]] | None = None, map_range_values: list[dict[str, Any]] | None = None, layer_range_values: dict[str, Any] | None = None, patch_size: str | None = None, clipping: dict[str, Any] | None = None, spatial_filter: dict[str, Any] | None = None, return_visible_only: bool = True, **kwargs) dict
Queries filtered legend information using the map’s current display.
The operation was introduced at ArcGIS Server 10.7.1. Supporting services require
bbox.clippingandspatial_filterrequire the corresponding service capability flags;time_relationrequiressupportsTimeRelation.
MapImageLayerManager
- class arcgis.layers.MapImageLayerManager(url: str, gis: GIS | None = None, map_img_lyr: MapImageLayer | None = None)
Bases:
_GISResourceAdministers an ArcGIS Online hosted cached map service.
The manager exposes the administrative operations used to edit service settings, manage cached tiles, and inspect tile generation jobs. Obtain an instance from the
managerproperty of a hostedMapImageLayer, or construct it with the service’s administrative URL ending in/MapServer.Parameter
Description
url
Required string. The administrative URL of the hosted map service, ending in
/MapServer. A trailing sublayer ID is removed.gis
Optional
GIS. The authenticated ArcGIS Online connection that owns or administers the service.map_img_lyr
Optional
MapImageLayer. The associated layer to refresh when service metadata changes.Example:
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS("home") item = gis.content.get("0123456789abcdef0123456789abcdef") map_image_layer = MapImageLayer.fromitem(item) manager = map_image_layer.manager type(manager)
Output:
arcgis.layers.MapImageLayerManager
- cancel_job(job_id: str) dict
Cancels a running tile update job for the hosted map service.
Parameter
Description
job_id
Required string. The ID returned by a tile operation or listed by
jobs().- Returns:
A dictionary containing
successwhen the request succeeds, or REST error details when it fails.
Example:
result = manager.cancel_job( "e2e8a0bb-4b40-46ac-813a-0bbdf522195f" ) result
Output:
{'success': True}
- delete_tiles(levels: str | list[int] | None = None, extent: str | dict[str, Any] | None = None) dict
Deletes selected levels and extents from the existing cache.
Parameter
Description
levels
Optional string or list of integers. The levels to delete, such as
"0-5,10,11-20"or[1, 2, 3].extent
Optional string or dictionary. Limits deletion to the specified extent. If omitted, deletion uses the full service extent.
- Returns:
A dictionary containing service and tile job information, including
statusandjobId, or REST error details.
Example:
from arcgis.layers import MapImageLayer from arcgis.gis import GIS gis = GIS("home") layer = MapImageLayer.fromitem(gis.content.get("<service-item-id>")) result = layer.manager.delete_tiles( levels="11-20", extent={ "xmin": 6224324.09, "ymin": 487347.52, "xmax": 11473407.69, "ymax": 4239488.36, "spatialReference": {"wkid": 102100}, }, ) result["jobId"]
Output:
'<job-id>'
- edit_tile_service(service_definition: str | dict[str, Any] | None = None, min_scale: float | None = None, max_scale: float | None = None, source_item_id: str | None = None, export_tiles_allowed: bool | None = None, max_export_tile_count: int | None = None) dict
Updates properties of the hosted cached map service.
Parameter
Description
service_definition
Optional string or dictionary. A partial service definition containing properties to update.
min_scale
Optional float. Sets the service minimum scale for caching.
max_scale
Optional float. Sets the service maximum scale for caching.
source_item_id
Optional string. The item ID of the source map service for the map image layer.
export_tiles_allowed
Optional boolean. Enables or disables tile exports. Explicit
Falsevalues are preserved.max_export_tile_count
Optional integer. Sets
maxExportTilesCount, the maximum number of tiles exported by one request.Unspecified values are omitted and do not reset existing service settings.
- Returns:
A dictionary containing
successwhen the update succeeds, or REST error details when it fails.
Example:
from arcgis.layers import MapImageLayer from arcgis.gis import GIS gis = GIS("home") layer = MapImageLayer.fromitem(gis.content.get("<service-item-id>")) result = layer.manager.edit_tile_service( service_definition={"cacheOnDemand": False}, export_tiles_allowed=True, max_export_tile_count=10000, ) result
Output:
{'success': True}
- import_tiles(item: Item | str, levels: str | list[int] | None = None, extent: str | dict[str, Any] | None = None, merge: bool = False, replace: bool = False) dict
Imports tiles from a tile package item into the existing cached service.
Before running this operation:
Upload the TPK or TPKX and retain its item ID.
Ensure the package tiling scheme matches the target service.
Ensure every imported level of detail exists in the target service.
- job_statistics(job_id: str) dict
Returns cache-generation or cache-deletion statistics for a tile job.
Parameter
Description
job_id
Required string. The tile job ID.
- Returns:
A dictionary containing job status, progress, tile counts, timing, extent, and per-level statistics when available.
Example:
statistics = manager.job_statistics("<job-id>") statistics["jobStatus"]
Output:
'DONE'
- jobs() dict
Returns a summary of all tile jobs associated with the service.
Each entry includes a job ID, status, operation type, timestamps, level information, and extent when available.
- Returns:
A dictionary containing
totaland ajobslist.
Example:
jobs = manager.jobs() jobs["total"]
Output:
1
- refresh() dict
Clears the web server cache for the hosted map service and refreshes the associated layer metadata.
- Returns:
A dictionary containing
success.
Example:
result = manager.refresh() result
Output:
{'success': True}
- rerun_job(job_id: str, code: str) dict
Reruns all or part of a canceled tile job.
Parameter
Description
job_id
Required string. The ID of the tile job to rerun.
code
Required string. Selects the tasks to rerun. Supported values are
ALL,ERROR, andCANCELED. Values are case-insensitive.- Returns:
A dictionary containing
successwhen the request succeeds, or REST error details when it fails.- Raises:
ValueError – If
codeis notALL,ERROR, orCANCELED.
Example:
result = manager.rerun_job("<job-id>", code="ERROR") result
Output:
{'success': True}
- status() dict
Returns whether the hosted map service is started or stopped.
- Returns:
A dictionary containing the service
nameandstatus.
Example:
status = manager.status() status
Output:
{'name': 'WorldService', 'status': 'Started'}
- update_tiles(levels: str | list[int] | None = None, extent: str | dict[str, Any] | None = None, merge: bool = False, replace: bool = False) dict | None
Starts tile generation for selected cache levels and an optional extent.
Note
The
update_tilesoperation is for ArcGIS Online only.Parameter
Description
levels
Optional string or list of integers. The cache levels to generate, such as
"0-5,10"or[0, 1, 2].extent
Optional string or dictionary. The tile cooking extent as
xmin,ymin,xmax,ymaxor an extent dictionary.merge
Optional boolean. The default is
Falseand applies to compact cache storage format. It controls whether the bundle files from the TPK file are merged with the one in the existing cached service. Otherwise, the bundle files are overwritten.replace
Optional boolean. The default is
False, applies to compact cache storage format and used when merge=true. It controls whether the new tiles will replace the existing ones when merging bundles.- Returns:
A dictionary containing service and tile job information, including
statusandjobId. ReturnsNonewhen the GIS is not ArcGIS Online.
Example:
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS("home") layer = MapImageLayer.fromitem(gis.content.get("<service-item-id>")) result = layer.manager.update_tiles( levels="11-20", extent="6224324.09,487347.52,11473407.69,4239488.36", ) result["status"]
Output:
'Success'
EnterpriseMapImageLayerManager
- class arcgis.layers.EnterpriseMapImageLayerManager(url, gis=None, map_img_lyr=None)
Bases:
_GISResourceAdministers an ArcGIS Enterprise map service.
This manager uses the ArcGIS Server Administrator API to manage the service lifecycle, service definition, runtime provider, and map cache. The authenticated user must have permission to administer the service. This manager uses the ArcGIS Server Administrator API to manage the service lifecycle, service definition, runtime provider, and map cache for a map service. The authenticated user must have permission to administer the service to initialize objects of this class.
While technically possible to initialize objects using the class directly and entering the map service admin url endpoint for the url argument, objects of this class are not typically initialized directly, but instead are accessed through the
managerproperty ofMapImageLayerinstances. See code example below the parameter table.Parameter
Description
url
Required string. The Server Administrator URL of the map service, ending in
/admin/services/<folder>/<service>.MapServeror/admin/services/<service>.MapServerfor a root-folder service.gis
Optional
GIS. The authenticated Enterprise GIS whose federated ArcGIS Server hosts the service. Administrative operations generally require an authenticated administrator.map_img_lyr
Optional
MapImageLayer. The associated public map service. Cache-building operations require this value and it is supplied automatically when the manager is obtained from a layer.Example: Initialize a manager from an Enterprise Map Image Layer
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS("home") item = gis.content.get("0123456789abcdef0123456789abcdef") map_image_layer = MapImageLayer.fromitem(item) manager = map_image_layer.manager type(manager)
Output:
arcgis.layers.EnterpriseMapImageLayerManager
- build_cache(levels: str | float | list[float], extent: str | dict[str, Any] | None = None, area_of_interest: Polygon | Envelope | list[Polygon | Envelope] | None = None) dict
Builds or rebuilds tiles in an ArcGIS Enterprise map service cache.
The cache schema must already exist. This operation runs the Manage Map Cache Tiles task through the server’s
System/CachingControllersgeoprocessing service usingRECREATE_ALL_TILES.Note
If neither
extentnorarea_of_interestis provided, the full extent of the map is used. Thearea_of_interesttakes precedence overextentif both are supplied.Parameter
Description
levels
Required string, float, or list of floats. One or more cache scales to build. The scales must exist in the service’s tiling scheme. Existing cache scales can be inspected through
MapImageLayer.properties.tileInfo.lods.Multiple values supplied as a list are converted internally to the semicolon-delimited format required by the caching service.
extent
Optional string or dictionary. A rectangular extent limiting the area whose tiles are generated. A dictionary should contain
xmin,ymin,xmax,ymax, and the appropriatespatialReferencekey-value pairs.area_of_interest
Optional
Polygonor list ofPolygonobjects limiting the area for which tiles are generated.- Returns:
A dictionary returned by the Enterprise cache reporting service. Its
statuskey can have a value of:EXISTSNONECOMPLETEDFAILEDFAILUREFAILING
- Raises:
ValueError – If neither
extentnorarea_of_interestis supplied.
Example:
from arcgis.gis import GIS gis = GIS(profile="your_enterprise_admin_profile") msvc_item = gis.content.search("Damage*", "Map Service")[0] map_img_lyr = msvc_item.layers[0].container map_img_mgr = map_img_lyr.manager level_list= [ l["scale"] for l in map_img_lyr.properties.tileInfo["lods"] if l["level"] > 4 and l["level"] < 7 ] cache_job_ext = map_img_mgr.build_cache( levels=level_list, extent={ "xmin": -13227632.572099, "ymin":3949348.377438, "xmax":-13004597.587167, "ymax":4095641.048130, } ) cache_job_ext
Output:
{'name': 'sd_pub_api/AGOL_DynamicMS', 'type': 'MapServer', 'status': 'EXISTS', 'lodInfos': [{'scale': 591657527.591555, 'levelID': 0, 'pixelSize': 156543.033928, 'percent': 0, 'expectedTileCount': 1, 'tileCount': 0, 'status': 'Empty', 'tilesSize': 0, 'isRunning': 'false'}, ... {'scale': 18489297.737236, 'levelID': 5, 'pixelSize': 4891.96981024998, 'percent': 100, 'expectedTileCount': 1, 'tileCount': 1, 'status': 'Complete', 'tilesSize': 2737, 'isRunning': 'false'}, {'scale': 9244648.868618, 'levelID': 6, 'pixelSize': 2445.98490512499, 'percent': 100, 'expectedTileCount': 2, 'tileCount': 2, 'status': 'Complete', 'tilesSize': 6782, 'isRunning': 'false'}], 'cacheExecutionStatus': 'NONE'}
- change_provider(provider: str) bool
Changes the runtime provider and instance model used by the service.
Current ArcGIS Enterprise releases use
ArcObjects11for dedicated instances andDMapsfor the shared instance pool. Only compatible services published from ArcGIS Pro can switch between these providers.ArcObjectsidentifies the legacy ArcMap service runtime. It is relevant only to supported releases from ArcGIS Enterprise 10.7 through 10.9.1, including migration toArcObjects11. The ArcMap runtime was removed at ArcGIS Enterprise 11.0 andArcObjectscan no longer be used there. Services using providers such asSDSmay not be eligible to change their instance type.Parameter
Description
provider
Required string.
ArcObjects11selects dedicated instances;DMapsselects shared instances.ArcObjectsis a legacy value for supported pre-11.0 deployments.- Returns:
A boolean when the server response contains a success value; otherwise, the unmodified response dictionary.
Example:
result = manager.change_provider("DMaps") result
Output:
True
- create_cache_schema(cache_directory: str, levels: str | float | list[float], tile_origin: str = '0 0', storage_format: str = 'COMPACTV2', cache_format: str = 'PNG8', tile_compression_quality: int = 0, dpi: int = 96, tile_width: int = 256, tile_height: int = 256, use_local_cache_dir: bool = True, lerc_error: float = 0, ready_to_serve_format: bool = False) str
Creates the tiling scheme and preparatory folders for an Enterprise map service cache.
This operation uses the Create Map Cache task from the server’s
System/CachingToolsgeoprocessing service. After the cache schema is created, usebuild_cache()to generate the cache tiles.Parameter
Description
cache_directory
Required string. The registered ArcGIS Server cache directory in which the cache will be created.
levels
Required string, float, or list of floats. The cache scales to define. Multiple scales can be supplied as a list and are converted internally to the semicolon-delimited format required by the caching service.
tile_origin
Optional string. The upper-left origin of the tiling scheme in map units. The default is
"0 0".storage_format
Optional string. The cache storage format. The default is
"COMPACTV2".cache_format
Optional string. The cache tile image format. The default is
"PNG8".tile_compression_quality
Optional integer. The compression quality used for applicable cache image formats.
dpi
Optional integer. The cache DPI. The default is
96.tile_width
Optional integer. Tile width in pixels. The default is
256.tile_height
Optional integer. Tile height in pixels. The default is
256.use_local_cache_dir
Optional boolean. Controls whether the server uses a local cache directory while generating tiles.
lerc_error
Optional float. The LERC error value used when applicable.
ready_to_serve_format
Optional boolean. Controls whether the cache is created using the ready-to-serve cache format.
- Returns:
The output map service URL returned by the caching service.
Example:
manager.create_cache_schema( cache_directory=r"C:\arcgisserver\directories\arcgiscache", levels=[ 18489297.737236001, 9244648.8686180003, ], )
- delete_cache() str
Deletes the entire cache for the Enterprise map service.
This operation deletes all cached tiles, associated cache files, and the cache schema.
After the cache is deleted, the map service is restarted.
Warning
This operation is destructive and cannot be undone. To use the service as a cached map service again, a new cache schema must be created before generating tiles.
- Returns:
The output map service URL returned by the Enterprise caching service.
Example:
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS(profile="your_enterprise_admin_profile") item = gis.content.get("<item_id>") map_image_layer = MapImageLayer.fromitem(item) manager = map_image_layer.manager manager.delete_cache()
- edit(service_dictionary: dict) bool
Updates the administrative definition of the map service.
Submit the complete JSON representation of the service, including unchanged properties. Other than
serviceNameandtype, values omitted from the dictionary are not persisted by ArcGIS Server. Editing restarts the service and can make it temporarily unavailable.Parameter
Description
service_dictionary
Required dictionary. The complete ArcGIS Server service definition containing the required updates.
- Returns:
A two-value tuple. The first value indicates whether ArcGIS Server reported success; the second contains the complete response dictionary.
Example:
service_definition = dict(manager.properties) service_definition["description"] = "Updated map service" success, response = manager.edit(service_definition) success
Output:
True
- property lifecycleinfo: dict
Returns lifecycle information for the service.
This resource requires ArcGIS Enterprise 11.1 or later. The response is a Python dictionary with a
lifecycleinfoskey whose values is a list with information on events such as service creation, edits, starts, and stops. Each event can include the user, event type, and atimestampexpressed as Unix epoch milliseconds. The dictionary also has alastmodifiedkey whose timestamp value identifies the most recent event time within the lifecycle.- Returns:
A Python dictionary returned by the service’s
lifecycleinfosadministrative resource. The dictionary has two keys, lifecycleinfos and lastmodified.
Example: Show the lifecyle information for a Map Service
from arcgis.gis import GIS from arcgis.layers import MapImageLayer gis = GIS(profile="your_enterprise_admin_profile") map_svc_item = gis.content.get("<item_id>") map_img_lyr = MapImageLayer.fromitem(map_svc_item) map_img_mgr = map_img_lyr.manager lifecycle = map_img_mgr.lifecycleinfo lifecycle
Output:
{'lifecycleinfos': [{'user': '0123456789ABCDEF::admin::arcgisonline', 'timestamp': 1786121934441, 'type': 'created'}, {'user': '0123456789ABCDEF::admin::arcgisonline', 'timestamp': 1786565821994, 'type': 'started'}], 'lastmodified': 1787623169707}
- start()
Starts the map service.
ArcGIS Server creates the configured minimum service instances on each server machine in the site. When the minimum is zero, instances are created on demand as requests arrive.
- Returns:
Truewhen ArcGIS Server reports success,Falsewhen it reports failure, or the unmodified response dictionary when no status value is returned.
Example:
manager.start()
Output:
True
- stop()
Stops the map service on all reachable machines in the site.
Stopping removes all running instances. The service cannot process incoming requests until it is started again.
- Returns:
Truewhen ArcGIS Server reports success,Falsewhen it reports failure, or the unmodified response dictionary when no status value is returned.
Example:
manager.stop()
Output:
True
- update_tiles(levels: str | float | list[float], extent: str | dict[str, Any] | None = None, area_of_interest: Polygon | list[Polygon] | None = None, update_mode: str = 'RECREATE_ALL_TILES') dict
Starts tile generation for selected cache levels and an optional extent on the Enterprise map service.
Parameter
Description
levels
Required string, float, or list of floats. The cache scales to update. Values must correspond to scales in the existing cache tiling scheme.
extent
Optional string or dictionary. A rectangular extent limiting the tiles that are updated.
area_of_interest
Optional
Polygonor list ofPolygons. A polygon or list of polygons limiting the tiles that are updated. If supplied withextent, the area of interest takes precedence.update_mode
Optional string. Controls how tiles are updated.
RECREATE_ALL_TILESreplaces existing tiles and createstiles that do not already exist.
RECREATE_EMPTY_TILEScreates only missing tiles and leavesexisting tiles unchanged.
DELETE_TILESremoves existing tiles and leaves missing tiles unchanged.
The default is
RECREATE_ALL_TILES.- Returns:
A dictionary returned by the Enterprise cache reporting service.
- Raises:
ValueError – If
update_modeis notRECREATE_ALL_TILES,RECREATE_EMPTY_TILES, orDELETE_TILES.
MapTable
- class arcgis.layers.MapTable(url: str, gis: GIS | None = None, container: MapImageLayer | None = None, dynamic_layer: dict | None = None, time_filter: datetime | str | list[datetime | str | None] | tuple[datetime | str | None, ...] | None = None)
Bases:
MapFeatureLayerRepresents a nonspatial table in a map service.
Exposes the rows and fields of a
Tableresource below aMapServerendpoint. Rows are returned asFeatureobjects with attributes but no geometry.Instances are normally obtained from the tables property of a
object, or created with theMapServiceLayerclass.Query functionality depends on the table’s data source and advertised service properties. Inspect
capabilities,supportsStatistics, andadvancedQueryCapabilitiesin the properties of the MapTable before using statistics, ordering, distinct values, pagination, historic moments, ranges, parameterized filters, or newer ArcGIS REST query parameters.Example: Inspecting properties of MapTable
mtable.properties.capabilities
Output:
'Query,Data'
Parameter
Description
url
Required string. The URL of the table resource, typically ending in
/MapServer/<table-id>.gis
Optional
GIS. The GIS used to access the service. A GIS is required for secured services. If omitted, the active GIS is used or an anonymous GIS is created.container
Optional
MapImageLayer. The map image layer containing this table.dynamic_layer
Optional dictionary. A dynamic table definition. The containing map service must advertise
supportsDynamicLayersasTrue.time_filter
Optional datetime, string, list, or tuple. A time instant or two-value time extent used by supported requests.
- classmethod fromitem(item: Item, table_id: int = 0) MapTable
Creates a map table from a map service item.
Parameter
Description
item
Required
Item. An item whose type isMap Service.table_id
Optional integer. The zero-based position of the table in the item’s
tablescollection. The default is0.- Returns:
The selected
MapTable.
Example:
from arcgis.layers import MapTable from arcgis.gis import GIS gis = GIS("home") map_service_item = gis.content.get("2aaddab96684405880d27f5261125061") map_table = MapTable.fromitem( item=map_service_item, table_id=0, ) isinstance(map_table, MapTable)
Output:
True
- query(where: str = '1=1', out_fields: str | list[str] = '*', time_filter: datetime | list[datetime] | list[str] | dict[datetime] | None = None, return_count_only: bool = False, return_ids_only: bool = False, return_distinct_values: bool = False, group_by_fields_for_statistics: str | None = None, statistic_filter: StatisticFilter | None = None, result_offset: int | None = None, result_record_count: int | None = None, object_ids: str | None = None, gdb_version: str | None = None, order_by_fields: list[str] | str | None = None, out_statistics: list[dict] | None = None, return_all_records: bool = True, historic_moment: int | datetime | None = None, sql_format: str | None = None, return_exceeded_limit_features: bool | None = None, as_df: bool = False, range_values: list[dict[str, Any]] | None = None, parameter_values: list[dict[str, Any]] | None = None, **kwargs) FeatureSet | int | dict | DataFrame
Queries rows using SQL, temporal, or statistical criteria.
Available options depend on the table’s data source and advertised
capabilities,supportsStatistics, andadvancedQueryCapabilitiesproperties.Example: Retrieving specific information from MapTable properties
mtable_object.properties.supportsStatistics
Parameter
Description
where
Optional string. The SQL where clause. The default is
1=1.out_fields
Optional string or list of strings. Fields to return. A comma-separated string is accepted. The default is
*.time_filter
Optional datetime, list, or string. A time instant or two-value time extent. Datetimes are converted to Unix epoch milliseconds.
return_count_only
Optional boolean. If
True, returns the number of matching rows.time_filter=[<startTime>, <endTime>]
Specified as
datetime.date,datetime.datetimeortimestampin milliseconds.import datetime as dt time_filter = [dt.datetime(2022, 1, 1), dt.datetime(2022, 1, 12)]
return_ids_only
Optional boolean. If
True, returns the object ID field name and matching object IDs in a dictionary.return_distinct_values
Optional boolean. If
True, returns distinct combinations of the requested fields. The table must advertise distinct-query support.group_by_fields_for_statistics
Optional string. Comma-separated fields used to group statistical results.
statistic_filter
Optional
StatisticFilter. A statistical definition used to populateoutStatistics.result_offset
Optional integer. Rows to skip when pagination is supported and
return_all_recordsisFalse.result_record_count
Optional integer. Maximum rows to return when pagination is supported and
return_all_recordsisFalse.object_ids
Optional string. A comma-separated list of object IDs to query.
gdb_version
Optional string. The geodatabase version to query for a versioned table. If omitted, the published version is used.
order_by_fields
Optional string or list of strings. Fields and
ASCorDESCdirections used to order results.order_by_fields = "STATE_NAME ASC, POP2000 DESC"
out_statistics
Optional list of dictionaries. Field-based statistics to calculate.
out_statistics = [ { "statisticType": "<count | sum | min | max | avg | stddev | var>", "onStatisticField": "Field1", "outStatisticFieldName": "Out_Field_Name1" },{ "statisticType": "<count | sum | min | max | avg | stddev | var>", "onStatisticField": "Field2", "outStatisticFieldName": "Out_Field_Name2" } ]
return_all_records
Optional boolean. If
True, requests all matching rows across service result pages. The default isTrue; pagination arguments are ignored in this mode.Note
See Query (Feature Service/Layer) for full explanation of layer properties. Use
propertiesto examine layer properties.If historic_moment is not specified, the query will apply to the current features.
historic_moment
Optional integer or datetime. An archive moment expressed as epoch milliseconds or a datetime. Requires archive-enabled data and
supportsQueryWithHistoricMoment.sql_format
Optional string. SQL syntax:
none,standard, ornative. Availability depends on the service and data source.return_exceeded_limit_features
Optional boolean. Controls whether rows are included when the service reports that its transfer limit was exceeded.
as_df
Optional boolean. If
True, returns row results as a pandasDataFrame. The default isFalse.range_values
Optional list of dictionaries. Named range instants or extents for a table with authored
rangeInfos. ANoneendpoint is open.range_values = [ { "name": "range name", "value": <value> or [ <value1>, <value2> ] }, { "name": "range name 2", "value": <value> or [ <value3>, <value4>] } } ]
Note
None is allowed in value-range case – that means infinity
# all features with values <= 1500 range_values = [ {"name": "elevation", "value": [1000, None]} ] # all features with values >= 1000 >>> range_values = {"name" : "range name", "value" : [1000, None]}
parameter_values
Optional list of dictionaries. Values for filters authored in
parameterInfos. Omitted values use authored defaults.kwargs
Optional keyword arguments. Additional supported Query (Map Service/Layer) parameters using ArcGIS REST names. Explicit named arguments take precedence over duplicate keys.
- Returns:
A
FeatureSetcontaining matching rows, a pandasDataFramewhenas_df=True, an integer for a count-only query, or a dictionary for IDs and other service response modes.
Example:
from arcgis.layers import MapTable from arcgis.gis import GIS gis = GIS("home") map_service_item = gis.content.get("2aaddab96684405880d27f5261125061") map_table = MapTable.fromitem(map_service_item, table_id=0) query_count = map_feature_layer.query(where "1=1", text = "Hurricane Data", units = "esriSRUnit_Meter", return_count_only = True, out_statistics = [ { "statisticType": "count", "onStatisticField": "Field1", "outStatisticFieldName": "Out_Field_Name1" }, { "statisticType": "avg", "onStatisticField": "Field2", "outStatisticFieldName": "Out_Field_Name2" } ], range_values= [ { "name": "range name", "value": [None, 1500] }, { "name": "range name 2", "value":[1000, None] } } ] ) query_count
Output:
149
VectorTileLayer
- class arcgis.layers.VectorTileLayer(url, gis, parent_url=None)
Bases:
LayerA Vector Tile Layer is a type of data layer used to access and display tiled data and its corresponding styles. This is stored as an item in ArcGIS and is used to access a vector tile service. Layer data include its name, description, and any overriding style definition.
- export_tiles(levels: str | None = None, export_extent: dict[str, Any] | None = None, polygon: dict[str, Any] | Polygon | None = None, create_item: bool = False) str | Item
Export vector tile layer
Parameter
Description
levels
Optional string.Specifies the tiled service levels to export. The values should correspond to Level IDs. The values can be comma-separated values or a range of values. Ensure that the tiles are present at each specified level.
# Example: # Comma-separated values >>> levels=1,2,3,4,5,6,7,8,9 //Range values >>> levels=1-4, 7-9
export_extent
Optional dictionary of the extent (bounding box) of the vector tile package to be exported. The extent should be within the specified spatial reference. The default value is the full extent of the tiled map service.
# Example: >>> export_extent = { "xmin": -109.55, "ymin" : 25.76, "xmax": -86.39, "ymax" : 49.94, "spatialReference": {"wkid": 4326} }
polygon
Optional dictionary. Introduced at 10.7. A JSON representation of a polygon, containing an array of rings and a spatialReference.
# Example: polygon = { "rings": [ [[6453,16815],[10653,16423], [14549,5204],[-7003,6939], [6453,16815]],[[914,7992], [3140,11429],[1510,10525], [914,7992]] ], "spatialReference": {"wkid": 54004} }
create_item
Optional boolean. Indicated whether an item will be created from the export (True) or a path to a downloaded file (False). Default is False. ArcGIS Online Only.
- Returns:
A list of exported item dictionaries or a single path
- classmethod fromitem(item) VectorTileLayer
The
fromitemmethod returns the layer at the specified index from a layerItemobject.Parameter
Description
item
Required Item. An item containing layers.
index
Optional int. The index of the layer amongst the item’s layers
- Returns:
The layer at the specified index.
# Usage Example >>> layer.fromitem(item="9311d21a9a2047d19c0faaebd6f2cca6", index=3)
- property info: list
The
infoproperty retrieves the relative paths to a list of resource files.- Returns:
A list of relative paths
- property manager: VectorTileLayerManager
The
managerproperty returns an instance ofVectorTileLayerManagerclass orEnterpriseVectorTileLayerManagerclass which provides methods and properties for administering this service.
- property styles: dict
The styles property returns styles for vector tiles in Mapbox GL Style specification version 8. The response for this styles resource includes the sprite and glyphs properties, with a relative path to the Vector Tile Sprite and Vector Tile Font resources. It also includes the version property, which represents the version of the style specification.
- tile_fonts(fontstack: str, stack_range: str) str
The
tile_fontsmethod retrieves glyphs in protocol buffer format.Parameter
Description
fontstack
Required string.
Note
The template url for this font resource is represented in the Vector Tile Style resource.
stack_range
Required string that depict a range. Ex: “0-255”
- Returns:
Glyphs in PBF format
- property tile_map: dict
The tile_map property describes a quadtree of tiles and can be used to avoid requesting tiles that don’t exist in the server. Each node of the tree has an associated tile. The root node (lod 0) covers the entire extent of the data. Children are identified by their position with NW, NE, SW, and SE. Tiles are identified by lod/h/v, where h and v are indexes on a 2^lod by 2^lod grid . These values are derived from the position in the tree. The tree has a variable depth. A node doesn’t have children if the complexity of the data in the associated tile is below a threshold. This threshold is based on a combination of number of features, attributes, and vertices.
- tile_sprite(out_format: str = 'sprite.json') dict
The
tile_spriteresource retrieves sprite images and metadata.Parameter
Description
out_format
Optional string. Default is “sprite.json”.
Values:
sprite.json|sprite.png|sprite@2x.png- Returns:
Sprite image and metadata.
- vector_tile(level: int, row: int, column: int) str
The
vector_tilemethod represents a single vector tile for the map.Note
The bytes for the tile at the specified level, row and column are returned in PBF format. If a tile is not found, an error is returned.
Parameter
Description
level
Required string. A level number as a string.
row
Required string. Number of the row that the tile belongs to.
column
Required string. Number of the column that tile belongs to.
- Returns:
Bytes in PBF format
VectorTileLayerManager
- class arcgis.layers.VectorTileLayerManager(url, gis=None, vect_tile_lyr=None)
Bases:
_GISResourceThe
VectorTileLayerManagerclass allows administration (if access permits) of ArcGIS Online Hosted Vector Tile Layers. A Hosted Vector Tile Service is published through a Feature Layer and these methods can only be applied to such Vector Tile Services. AVectorTileLayeroffers access to layer content.Note
Url must be admin url such as:
https://services.myserver.com/arcgis/rest/admin/services/serviceName/VectorTileServer/- cancel_job(job_id: str) dict
The cancel operation supports cancelling a job while update tiles is running from a hosted feature service. The result of this operation is a response indicating success or failure with error code and description.
- delete_job(job_id: str) dict
This operation deletes the specified asynchronous job being run by the geoprocessing service. If the current status of the job is SUBMITTED or EXECUTING, it will cancel the job. Regardless of status, it will remove all information about the job from the system. To cancel a job in progress without removing information, use the Cancel Job operation.
- delete_tiles()
The
delete_tilesmethod deletes tiles from the current cache.Note
The
delete_tilesoperation is for ArcGIS Online only and can only be used for a Vector Tile Layer published from a service directory.- Returns:
A dictionary
# USAGE EXAMPLE >>> from arcgis.layers import VectorTileLayer >>> from arcgis.gis import GIS # connect to your GIS >>> gis = GIS(url, username, password) >>> vector_layer_item = gis.content.get('abcd_item-id') >>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item) >>> vtl_manager = vector_tile_layer.manager >>> deleted_tiles = vtl_manager.delete_tiles() >>> type(deleted_tiles)
- edit_tile_service(source_item_id: str | None = None, export_tiles_allowed: bool | None = None, min_scale: float | None = None, max_scale: float | None = None, max_export_tile_count: int | None = None, layers: list[dict] | None = None, cache_max_age: int | None = None, max_zoom: int | None = None) dict
The edit operation enables editing many parameters in the service definition as well as the source_item_id which can be found by looking at the Vector Tile Layer’s related items.
Parameter
Description
source_item_id
Optional String. The item id of the vector tile service.
export_tiles_allowed
Optional boolean.
exports_tiles_allowedsets the value to let users export tilesmin_scale
Optional float. Sets the services minimum scale for caching. At the moment this parameter can only be set if the Vector Tile Layer was published through a service directory.
max_scale
Optional float. Sets the services maximum scale for caching. At the moment this parameter can only be set if the Vector Tile Layer was published through a service directory.
max_export_tile_count
Optional int.
max_export_tile_countsets the maximum amount of tiles to be exported from a single call.layers
Optional list of dictionaries. Each dict representing a layer.
Syntax Example:
layers = [{“name”: “Layer Name”,“id”: 1159321,“layerId”: 0,“tableName”: “tableName”,“type”: “Feature Layer”,“xssTrustedFields”: “”}]cache_max_age
Optional int. The maximum cache age. At the moment this parameter can only be set if the Vector Tile Layer was published through a feature service.
max_zoom
Optional int. The maximum zoom level. At the moment this parameter can only be set if the Vector Tile Layer was published through a feature service.
# USAGE EXAMPLE >>> from arcgis.layers import VectorTileLayer >>> from arcgis.gis import GIS # connect to your GIS and get the tile layer item >>> gis = GIS(url, username, password) >>> vector_layer_item = gis.content.get('abcd_item-id') >>> source_item_id = vector_tile_item.related_items(rel_type="Service2Data", direction="forward")[0]["id"] >>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item) >>> vtl_manager = vector_tile_layer.manager >>> vtl_manager.edit_tile_service( min_scale = 50, max_scale = 100, source_item_id = source_item_id, export_tiles_allowed = True, max_Export_Tile_Count = 10000 )
- job_statistics(job_id: str) dict
The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.
- jobs() dict
The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.
- rebuild_cache()
The rebuild_cache operation update the vector tile layer cache to reflect any changes made to the feature layer used to publish this vector tile layer. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.
- rerun_job(code, job_id: str) dict
The
rerun_joboperation supports re-running a canceled job from a hosted map service. The result of this operation is a response indicating success or failure with error code and description.Parameter
Description
code
required string, parameter used to re-run a given jobs with a specific error code:
ALL | ERROR | CANCELEDjob_id
required string, job to reprocess
- Returns:
A boolean or dictionary
- status() dict
The status operation returns a dictionary indicating whether a service is started (available) or stopped.
- swap(target_service_name)
The swap operation replaces the current service cache with an existing one.
Note
The
swapoperation is for ArcGIS Online only and can only be used for a Vector Tile Layer published from a service directory.Parameter
Description
target_service_name
Required string. Name of service you want to swap with.
- Returns:
Dictionary indicating success or error
- update_tiles(merge_bundle: bool = False) dict
The update_tiles operation supports updating the cooking extent and cache levels in a Hosted Vector Tile Service. The results of the operation is a response indicating success and a url to the Job Statistics page, or failure.
It is recommended to use the rebuild_cache method when your layer has been published through a Feature Layer since edits require regeneration of the tiles.
Parameter
Description
merge_bundle
Optional bool. Default is False. This parameter will only be set if the Vector Tile Layer has been published through a service directory.
- Returns:
Dictionary. If the product is not ArcGIS Online tile service, the result will be None.
# USAGE EXAMPLE >>> from arcgis.layers import VectorTileLayer >>> from arcgis.gis import GIS # connect to your GIS and get the web map item >>> gis = GIS(url, username, password) >>> vector_layer_item = gis.content.get('abcd_item-id') >>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item) >>> vtl_manager = vector_tile_layer.manager >>> update_tiles = vtl_manager.update_tiles() >>> type(update_tiles) <Dictionary>
EnterpriseVectorTileLayerManager
- class arcgis.layers.EnterpriseVectorTileLayerManager(url, gis=None, vect_tile_lyr=None)
Bases:
_GISResourceThe
EnterpriseVectorTileLayerManagerclass allows administration (if access permits) of ArcGIS Enterprise hosted vector tile layers. A Hosted Vector Tile Service is published through a Feature Layer and these methods can only be applied to such Vector Tile Services. AVectorTileLayeroffers access to layer content.Note
Url must be admin url such as:
https://services.myserver.com/arcgis/server/admin/services/serviceName.VectorTileServer/- change_provider(provider: str)
The changeProvider operation updates an individual service to use either a dedicated or a shared instance type. When a qualified service is published, the service is automatically set to use shared instances.
When using this operation, services may populate other provider types as values for the provider parameter, such as ArcObjects and SDS. While these are valid provider types, this operation does not support changing the provider of such services to either ArcObjects11 or DMaps. Services with ArcObjects or SDS as their provider cannot change their instance type.
Parameter
Description
provider
Optional String. Specifies the service instance as either a shared (“DMaps”) or dedicated (“ArcObjects11”) instance type. These values are case sensitive.
- Returns:
Boolean
- delete()
This operation deletes an individual service, stopping the service and removing all associated resources and configurations.
- edit(service_dictionary)
This operation edits the properties of a service. To edit a service, you need to submit the complete JSON representation of the service, which includes the updates to the service properties. Editing a service can cause the service to be restarted with updated properties.
The JSON representation of a service contains the following four sections:
Service description properties—Common properties that are shared by all services. These properties typically identify a specific service.
Service framework properties—Properties targeted toward the framework that hosts the GIS service. They define the life cycle and load balancing of the service.
Service type properties—Properties targeted toward the core service type as seen by the server administrator. Since these properties are associated with a server object, they vary across the service types.
Extension properties—Represent the extensions that are enabled on the service.
Note
The JSON is submitted to the operation URL as a value of the parameter service. You can leave out the serviceName and type parameters in the JSON representation. Any other properties that are left out are not persisted by the server.
Note
If the service is currently running you need to stop the service before editing it. This can be done by calling the stop method on the service object. Once the service is stopped, you can edit the service and then start it again by calling the start method on the service object.
Parameter
Description
service_dictionary
Required dict. The JSON representation of the service and the properties that have been updated or added.
Example:
{“serviceName”: “RI_Fed2019_WM”,“type”: “VectorTileServer”,“description”: “”,“capabilities”: “TilesOnly,Tilemap”,“extensions”: [],“frameworkProperties”: {},“datasets”: []}- Returns:
boolean
- rebuild_cache(min_scale=None, max_scale=None)
The rebuild_cache operation updates the vector tile layer cache to reflect any changes made. The results of the operation is the url to the vector tile service once it is done rebuilding.
Parameter
Description
min_scale
Optional Float. Represents the minimum scale of the tiles. If nothing is provided, default value is used.
max_scale
Optional Float. Represents the maximum scale of the tiles. If nothing is provided, default value is used.
Working with OGC layers
CSVLayer
- class arcgis.layers.CSVLayer(url: Item | str, gis: GIS | None = None, **kwargs)
Bases:
BaseOpenDataRepresents a CSV File Hosted on a Server.
Parameter
Description
url
Required String or Item. The web address or
Itemto the CSV resource.gis
Optional
GIS. The GIS used to reference the service. Theactive_gisis used if not specified.copyright
Optional String. Describes limitations and usage of the data.
delimiter
Optional String. The separator value. This can be the following:
, (comma), ‘ ‘ (space), | (pipe), r (tab), or ; (semicolon).
fields
Optional List. An array of dictionaries containing the field information.
opacity
Optional Float. This value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
scale
Optional Tuple. The min/max scale of the layer where the positions are: (min, max) as float values.
sql_expression
Optional String. Optional query string to apply to the layer when displayed on the widget or web map.
title
Optional String. The title of the layer used to identify it in places such as the Legend and Layer List widgets.
- property delimiter: str
Gets/Sets the delimiter for the CSV Layer. The default is ,
Values
Description
,
comma
“ “
space
;
semicolon
|
pipe
r
tab
- Returns:
String
- property latitude: str
The latitude field name. If not specified, the class will look for following field names in the CSV source:
“lat”, “latitude”, “y”, “ycenter”, “latitude83”, “latdecdeg”, “POINT-Y”
- property longitude: str
The longitude field name. If not specified, the CSVLayer will look for following field names in the CSV source:
“lon”, “lng”,”long”, “longitude”, “x”, “xcenter”, “longitude83”, “longdecdeg”, “POINT-X”
- property opacity: float
Get/Set the opacity value.
Parameter
Description
value
Required float. Value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
- Returns:
Float
- property properties: dict
Returns the properties of the Layer.
- Returns:
dict
- property renderer: dict
Get/Set the Renderer of the CSV Layer
- Returns:
A
dictlike object used to update and alter JSON
- property scale
Gets/Sets the Min/Max Scale for the layer
Parameter
Description
value
Required tuple. (Min_value, Max_value)
- Returns:
A tuple (min, max)
- property sql_expression: str
The SQL where clause used to filter features on the client. Only the features that satisfy the definition expression are displayed in the widget. Setting a definition expression is useful when the dataset is large and you don’t want to bring all features to the client for analysis. The sql_expressions may be set when a layer is constructed prior to it loading in the view or after it has been loaded into the class.
- Returns:
String
- property title: str
Get/Set the title of the layer used to identify it in places such as the Legend and LayerList widgets.
Parameter
Description
value
Required string. Name of title
- Returns:
String
GeoJSONLayer
- class arcgis.layers.GeoJSONLayer(url: str | None = None, data: str | dict | None = None, **kwargs)
Bases:
BaseOGCThe GeoJSONLayer class is used to create a layer based on GeoJSON. GeoJSON is a format for encoding a variety of geographic data structures. The GeoJSON data must comply with the RFC 7946 specification which states that the coordinates are in spatial reference: WGS84 (wkid 4326).
Parameter
Description
url
Optional String. The web location of the GeoJSON file.
data
Optional String or Dict. A path to a GeoJSON file, the GeoJSON data as a string, or the GeoJSON data as a dictionary.
copyright
Optional String. Describes limitations and usage of the data.
opacity
Optional Float. This value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
renderer
Optional Dictionary. A custom set of symbology for the given geojson dataset.
scale
Optional Tuple. The min/max scale of the layer where the positions are: (min, max) as float values.
title
Optional String. The title of the layer used to identify it in places such as the Legend and Layer List widgets.
- property opacity: float
Get/Set the opacity value.
Parameter
Description
value
Required float. Value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
- Returns:
Float
- property properties: dict
Returns the properties of the Layer.
- Returns:
dict
- property renderer: dict
Gets/Sets the renderer for the layer
- property scale
Gets/Sets the Min/Max Scale for the layer
Parameter
Description
value
Required tuple. (Min_value, Max_value)
- Returns:
A tuple (min, max)
- property title: str
Get/Set the title of the layer used to identify it in places such as the Legend and LayerList widgets.
Parameter
Description
value
Required string. Name of title
- Returns:
String
- property url: str
Get/Set the data associated with the GeoJSON Layer
- Returns:
String
GeoRSSLayer
- class arcgis.layers.GeoRSSLayer(url: str, **kwargs)
Bases:
BaseOGCThe GeoRSSLayer class is used to create a layer based on GeoRSS. GeoRSS is a way to add geographic information to an RSS feed. The GeoRSSLayer supports both GeoRSS-Simple and GeoRSS GML encodings, and multiple geometry types.
It exports custom RSS tags as additional attribute fields in the form of simple strings or an array of JSON objects.
Parameter
Description
url
Required String. The URL of the GeoRSS service.
copyright
Optional String. Describes limitations and usage of the data.
line_symbol
Optional Dict. The symbol for the polyline data in the GeoRSS.
opacity
Optional Float. This value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
point_symbol
Optional Dict. The symbol for the point data in the GeoRSS.
polygon_symbol
Optional Dict. The symbol for the polygon data in the GeoRSS.
title
Optional String. The title of the layer used to identify it in places such as the Legend and LayerList widgets.
scale
Optional Tuple. The min/max scale of the layer where the positions are: (min, max) as float values.
- property line_symbol: dict
Gets/Sets the Line Symbol for Polyline Geometries
- Returns:
InsensitiveDict: A case-insensitivedictlike object used to update and alter JSON A variants of a case-less dictionary that allows for dot and bracket notation.
- property opacity: float
Get/Set the opacity value.
Parameter
Description
value
Required float. Value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
- Returns:
Float
- property point_symbol: dict
Gets/Sets the Point Symbol for Point Geometries
- Returns:
A
dictobject used to update and alter JSON
- property polygon_symbol: dict
Gets/Sets the Polygon Symbol for Polygon Geometries
- Returns:
InsensitiveDict: A case-insensitivedictlike object used to update and alter JSON A variants of a case-less dictionary that allows for dot and bracket notation.
- property properties: dict
Returns the properties of the Layer.
- Returns:
dict
- property scale
Gets/Sets the Min/Max Scale for the layer
Parameter
Description
value
Required tuple. (Min_value, Max_value)
- Returns:
A tuple (min, max)
- property title: str
Get/Set the title of the layer used to identify it in places such as the Legend and LayerList widgets.
Parameter
Description
value
Required string. Name of title
- Returns:
String
OGCFeatureService
- class arcgis.layers.OGCFeatureService(url: str, gis: GIS = None)
Bases:
objectRepresents the Hosted OGC Feature Server
Parameter
Description
url
Required String. The web address endpoint.
gis
Optional
GIS. The connection object.- property collections: Iterator[OGCCollection]
Yields all the OGC Feature Service Layers within the service.
- Returns:
Iterator[
OGCCollection]
- property conformance: Dict[str, Any]
Provides the API conformance with the OGC standard.
- Returns:
Dict[str, Any]
- property properties: dict
returns the service properties
OGCCollection
- class arcgis.layers.OGCCollection(url: str, gis: GIS = None)
Bases:
objectRepresents a single OGC dataset
Parameter
Description
url
Required String. The web address endpoint.
gis
Optional
GIS. The connection object.- get(feature_id: int) Dict[str, Any]
Gets an individual feature on the service. Needs to correspond to an id of the feature.
- Returns:
Dict[str, Any]
- property properties: dict
returns the service properties
- query(query: str | None = None, limit: int = 10000, bbox: list[float] | None = None, bbox_sr: int | None = None, time_filter: str | None = None, return_all: bool = False, **kwargs) dict[str, Any] | DataFrame
Queries the
OGCFeatureServiceLayer and returns back the information as a Spatially Enabled DataFrame.Parameter
Description
query
Optional String. A SQL based query applied to the service.
limit
Optional Integer. The number of records to limit to. The default is 10,000.
bbox
Optional List[float]. The bounding box to limit search in.
bbox_sr
Optional Integer. The coordinate reference system as a WKID.
time_filter
Optional String. The dates to filter time by.
- Returns:
Union[Dict[str, Any], pd.DataFrame]
WMSLayer
- class arcgis.layers.WMSLayer(url, version='1.3.0', gis=None, **kwargs)
Bases:
BaseOGCRepresents a Web Map Service, which is an OGC web service endpoint.
Parameter
Description
url
Required string. The administration URL for the ArcGIS Server.
version
Optional String. The version number of the WMS service. The default is 1.3.0.
gis
Optional
GIS. The GIS used to reference the service by. The arcgis.env.active_gis is used if not specified.copyright
Optional String. Describes limitations and usage of the data.
scale
Optional Tuple. The min/max scale of the layer where the positions are: (min, max) as float values.
opacity
Optional Float. This value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
title
Optional String. The title of the layer used to identify it in places such as the Legend and Layer List widgets.
- property layers: list
Returns all layers from the WMS service, excluding the top-level group layer if present.
- property opacity: float
Get/Set the opacity value.
Parameter
Description
value
Required float. Value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
- Returns:
Float
- property properties: dict
Returns the properties of the Layer, including sublayers if present.
- Returns:
dict
- property scale
Gets/Sets the Min/Max Scale for the layer
Parameter
Description
value
Required tuple. (Min_value, Max_value)
- Returns:
A tuple (min, max)
- property title: str
Get/Set the title of the layer used to identify it in places such as the Legend and LayerList widgets.
Parameter
Description
value
Required string. Name of title
- Returns:
String
WMTSLayer
- class arcgis.layers.WMTSLayer(url, version='1.0.0', gis=None, is_google_compatible=False, **kwargs)
Bases:
BaseOGCRepresents a Web Map Tile Service, which is an OGC web service endpoint.
Parameter
Description
url
Required string. The web address of the endpoint.
version
Optional String. The version number of the WMTS service. The default is 1.0.0
gis
Optional
GIS. The GIS used to reference the service by. The arcgis.env.active_gis is used if not specified.copyright
Optional String. Describes limitations and usage of the data.
opacity
Optional Float. This value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
scale
Optional Tuple. The min/max scale of the layer where the positions are: (min, max) as float values.
title
Optional String. The title of the layer used to identify it in places such as the Legend and Layer List widgets.
- property opacity: float
Get/Set the opacity value.
Parameter
Description
value
Required float. Value can range between 1 and 0, where 0 is 100 percent transparent and 1 is completely opaque.
- Returns:
Float
- operational_layer_json(identifier: str) dict
Represents the JSON Format for the specified layer.
Parameter
Description
identifier
Required string. The layer’s Identifier to get the JSON format for.
You can find this by looping through the layers in the properties attribute.
- for lyr in wmts.properties[“Capabilities”][“Contents”][“Layer”]:
print(lyr[“Identifier”])
- Returns:
dict
- property properties: dict
Returns the properties of the Layer.
- Returns:
dict
- property scale
Gets/Sets the Min/Max Scale for the layer
Parameter
Description
value
Required tuple. (Min_value, Max_value)
- Returns:
A tuple (min, max)
- property title: str
Get/Set the title of the layer used to identify it in places such as the Legend and LayerList widgets.
Parameter
Description
value
Required string. Name of title
- Returns:
String
SymbolService
- class arcgis.layers._symbol.SymbolService(url: str, gis: GIS = None)
Bases:
objectSymbol service is an ArcGIS Server utility service that provides access to operations to build and generate images for Esri symbols to be consumed by internal and external web applications.
- generate_image(item: Item, name: str | None = None, dict_features: dict[str, Any] | None = None, size: str = '200,200', scale: float = 1, anchor: bool = False, image_format: str = 'png', dpi: int = 96, file_path: str | Path = None) str
Returns a single symbol based on a web style item.
Parameter
Description
item
Required Item. The web style ArcGIS Enterprise portal item ID. The web style must belong to the same organization the ArcGIS Server is federated to.
name
Optional String. The web style ArcGIS Enterprise portal item ID. The web style must belong to the same organization the ArcGIS Server is federated to.
dict_features
Optional dict[str, Any]. The attributes and configuration key and value pairs for dictionary-based styles.
size
Optional String. The size (width and height) of the exported image in pixels. If the size is not specified, the image will be constrained by the requested symbol’s size.
scale
Optional Float. A value of 1.0 implies the symbol is not scaled. Setting the value to 1.5 scales the image to 50 percent more than the image’s original size. Settings the value to 0.5 reduces the image’s original size by 50 percent. If both the size and scale parameters are specified, both changes will be honored; the symbol will be scaled to the value set for scale and resized to the value set for the size parameter.
anchor
Optional Bool. The symbol placement in the image. When set to true, the original symbol anchor point placement in the image is honored. When set to false, the symbol is centered to the image. Having the image centered can be useful if you want to preview the whole symbol without taking symbol offset or anchor points into account. The default value is false.
image_format
Optional String. The output image format. The default format is png. The allowed values are: png, png8, png24, png32, jpg, bmp, gif, svg, and svgz.
dpi
Optional Int. The device resolution of the exported image (dots per inch). If the dpi value is not specified, an image with a default DPI of 96 will be exported.
file_path
Optional String | pathlib.Path. The full save path with the file name to the save location. The folder must exist.
- Returns:
String