arcgis.mapping module¶
The arcgis.mapping module provides components for visualizing GIS data and analysis. This module includes WebMap and WebScene components that enable 2D and 3D mapping and visualization in the GIS. This module also includes mapping layers like MapImageLayer, SceneLayer and VectorTileLayer.
WebMap¶
-
class
arcgis.mapping.
WebMap
(webmapitem=None)¶ Bases:
traitlets.traitlets.HasTraits
,collections.OrderedDict
Represents a web map and provides access to its basemaps and operational layers as well as functionality to visualize and interact with them.
An ArcGIS web map is an interactive display of geographic information that you can use to tell stories and answer questions. Maps contain a basemap over which a set of data layers called operational layers are drawn. To learn more about web maps, refer: https://doc.arcgis.com/en/arcgis-online/reference/what-is-web-map.htm
Web maps can be used across ArcGIS apps because they adhere to the same web map specification. This means you can author web maps in one ArcGIS app (including the Python API) and view and modify them in another. To learn more about the web map specification, refer: https://developers.arcgis.com/web-map-specification/
Argument
Description
webmapitem
Optional Item object whose Item.type is ‘Web Map’. If not specified an empty WebMap object is created with some useful defaults.
# USAGE EXAMPLE 1: Creating a WebMap object from an existing web map item from arcgis.mapping import WebMap from arcgis.gis import GIS # connect to your GIS and get the web map item gis = GIS(url, username, password) wm_item = gis.content.get('1234abcd_web map item id') # create a WebMap object from the existing web map item wm = WebMap(wm_item) type(wm) >> arcgis.mapping._types.WebMap # explore the layers in this web map using the 'layers' property wm.layers >> [{}...{}] # returns a list of dictionaries representing each operational layer
-
add_layer
(layer, options=None)¶ Adds the given layer to the WebMap.
Argument
Description
layer
Required object. You can add:
Layer objects such as FeatureLayer, MapImageLayer, ImageryLayer etc.
Item objects and FeatureSet and FeatureCollections
Table objects
options
Optional dict. Specify properties such as title, symbol, opacity, visibility, renderer for the layer that is added. If not specified, appropriate defaults are applied.
# USAGE EXAMPLE: Add feature layer and map image layer item objects to the WebMap object. crime_fl_item = gis.content.search("2012 crime")[0] streets_item = gis.content.search("LA Streets","Map Service")[0] wm = WebMap() # create an empty web map with a default basemap wm.add_layer(streets_item) >> True # Add crime layer, but customize the title, transparency and turn off the default visibility. wm.add_layer(fl_item, {'title':'2012 crime in LA city', 'opacity':0.5, 'visibility':False}) >> True
- Returns
True if layer was successfully added. Else, raises appropriate exception.
-
add_table
(table, options=None)¶ Adds the given layer to the WebMap.
Argument
Description
table
Required object. You can add:
Table objects
options
Optional dict. Specify properties such as title, symbol, opacity, visibility, renderer for the table that is added. If not specified, appropriate defaults are applied.
wm = WebMap() table = Table('https://some-url.com/') wm.add_layer(table)
- Returns
True if table was successfully added. Else, raises appropriate exception.
-
property
basemap
¶ Base map layers in the web map
- Returns
List of layers as dictionaries
# Usage example 1: Get the basemap used in the web map from arcgis.mapping import WebMap wm = WebMap(wm_item) wm.basemap >> {"baseMapLayers": [ {"id": "defaultBasemap", "layerType": "ArcGISTiledMapServiceLayer", "url": "https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer", "visibility": true, "opacity": 1, "title": "Topographic" }], "title": "Topographic" } # Usage example 2: Set the basemap used in the web map from arcgis.mapping import WebMap wm = WebMap(wm_item) print(wm.basemaps) >> ['dark-gray', 'dark-gray-vector', 'gray', 'gray-vector', 'hybrid', 'national-geographic', 'oceans', 'osm', 'satellite', 'streets', 'streets-navigation-vector', 'streets-night-vector', 'streets-relief-vector', 'streets-vector', 'terrain', 'topo', 'topo-vector'] wm.basemap = 'dark-gray' print(wm.gallery_basemaps) >> ['custom_dark_gray_canvas', 'imagery', 'imagery_hybrid', 'light_gray_canvas', 'custom_basemap_vector_(proxy)', 'world_imagery_(proxy)', 'world_street_map_(proxy)'] wm.basemap = 'custom_dark_gray_canvas' # Usage example 3: Set the basemap equal to an item from arcgis.mapping import WebMap wm = WebMap(wm_item) # Use basemap from another item as your own wm.basemap = wm_item_2 wm.basemap = tiled_map_service_item wm.basemap = image_layer_item wm.basemap = wm2.basemap wm.basemap = wm2
-
property
basemap_switcher
¶ - Returns
True if Basemap switcher is enabled.
-
property
basemaps
¶ A list of possible basemaps to set for the map
-
property
bookmarks
¶ - Returns
True if bookmarks are enabled for dashboard widget.
-
property
events
¶ - Returns
list of events attached to the widget.
-
property
forms
¶ The smart forms corresponding to each layer and table in the web map.
- Returns
# Usage Example: Updating property of a form. wm = WebMap() wm.add_layer(table) forms = wm.forms form = forms.get(title="Manhole Inspection") form.title = "Manhole Inspection Form" form.update()
-
property
gallery_basemaps
¶ View your portal’s custom basemap group
-
get_layer
(item_id=None, title=None, layer_id=None)¶ Returns the first layer with a matching itemId, title, or layer_id in the webmap’s operational layers. Pass one of the three parameters into the method to return the layer.
Argument
Description
item_id
Optional string. Pass the item_id for the operational layer you are trying to reference in the webmap.
title
Optional string. Pass the title for the operational layer you are trying to reference in the webmap.
layer_id
Optional string. Pass the id for the operational layer you are trying to reference in the webmap.
- Returns
Layer as a dictionary
-
get_table
(item_id=None, title=None, layer_id=None)¶ Returns the first table with a matching itemId, title, or layer_id in the webmap’s tables. Pass one of the three parameters into the method to return the table.
Argument
Description
item_id
Optional string. Pass the item_id for the table you are trying to reference in the webmap.
title
Optional string. Pass the title for the table you are trying to reference in the webmap.
layer_id
Optional string. Pass the id for the table you are trying to reference in the webmap.
- Returns
Table as a dictionary
-
property
height
¶ - Returns
Height of the widget
-
property
layer_visibility
¶ - Returns
True if layer visibility is enabled for dashboard widget.
-
property
layers
¶ Operational layers in the web map
- Returns
List of Layers as dictionaries
# USAGE EXAMPLE 1: Get the list of layers from a web map from arcgis.mapping import WebMap wm = WebMap(wm_item) wm.layers >> [{"id": "Landsat8_Views_515", "layerType": "ArcGISImageServiceLayer", "url": "https://landsat2.arcgis.com/arcgis/rest/services/Landsat8_Views/ImageServer", ...}, {...}] len(wm.layers) >> 2
-
property
legend
¶ - Returns
True if legend visibility is enabled for dashboard widget.
- Returns
navigation enabled or disabled.
-
property
offline_areas
¶ Resource manager for offline areas cached for the web map :return:
-
property
pop_ups
¶ - Returns
True if popups are enabled for dashboard widget.
-
print
(file_format, extent, dpi=92, output_dimensions=(500, 500), scale=None, rotation=None, spatial_reference=None, layout_template='MAP_ONLY', time_extent=None, layout_options=None)¶ Prints the WebMap object to a printable file such as PDF, PNG32, JPG. The render and print operations happen server side (ArcGIS Online or Enterprise) and not on the client. This method takes the state of the web map, renders and returns either a page layout or a map without page surrounds of the specified extent in raster or vector format.
Argument
Description
file_format
Required string.Specifies the output file format. Valid types:
PNG8
|PNG32
|JPG
|GIF
|PDF
|EPS
|SVG
|SVGZ
.extent
Required dictionary.Specify the extent to be printed.
# Example Usage: >>> extent = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100}, 'xmin': -15199645.40582486, 'ymin': 3395607.5273594954, 'xmax': -11354557.134968376, 'ymax': 5352395.451459487}
The spatial reference of the extent object is optional; when it is not provided, it is assumed to be in the map’s spatial reference. When the aspect ratio of the map extent is different than the size of the map on the output page or the
output_dimensions
, you might notice more features on the output map.dpi
Optional integer.Specify the print resolution of the output file.
dpi
stands for dots per inch. A higher number implies better resolution and a larger file size.output_dimensions
Specify the dimensions of the output file in pixels. If the
layout_template
is notMAP_ONLY
, the specific layout template chosen takes precedence over this paramter.scale
Optional float.Specify the map scale to be printed. The map scale at which you want your map to be printed. This parameter is optional but recommended for optimal results. The
scale
property is especially useful when map services in the web map have scale-dependent layers or reference scales set. Since the map that you are viewing on the web app may be smaller than the size of the output map (for example, 8.5 x 11 in. or A4 size), the scale of the output map will be different and you could see differences in features and/or symbols in the web application as compared with the output map.When scale is used, it takes precedence over the extent, but the output map is drawn at the requested scale centered on the center of the extent.
rotation
Optional float.Specify the number of degrees by which the map frame will be rotated, measured counterclockwise from the north. To rotate clockwise, use a negative value.
spatial_reference
Optional dictionary.Specify the spatial reference in which map should be printed. When not specified, the following is the order of precedence:
read from the
extent
parameterread from the base map layer of your web map
read from the
layout_template
chosen
layout_template
Optional string.The default value
MAP_ONLY
does not use any template. To get the list of available templates runget_layout_templates()
.time_extent
Optional list.If there is a time-aware layer and you want it to be drawn at a specified time, specify this property. This order list can have one or two elements. Add two elements (
startTime
followed byendTime
) to represent a time extent, or provide only one time element to represent a time instant. Times are always in UTC.# Example Usage to represent Tues. Jan 1, 2008 00:00:00 UTC: # to Thurs. Jan 1, 2009 00:00:00 UTC. >>> time_extent = [1199145600000, 1230768000000]
layout_options
Optional dictionary.This defines settings for different available page layout elements and is only needed when an available
layout_template
is chosen. Page layout elements includetitle
,copyright text
,scale bar
,author name
, andcustom text elements
. For more details, see ExportWebMap specification.- Returns
URL to the file which can be downloaded and printed.
# USAGE EXAMPLE 1: Printing a web map to a JPG file of desired extent. from arcgis.mapping import WebMap from arcgis.gis import GIS # connect to your GIS and get the web map item gis = GIS(url, username, password) wm_item = gis.content.get('1234abcd_web map item id') # create a WebMap object from the existing web map item wm = WebMap(wm_item) # create an empty web map wm2 = WebMap() wm2.add_layer(<desired Item or Layer object>) # set extent redlands_extent = {'spatialReference': {'latestWkid': 3857, 'wkid': 102100}, 'xmin': -13074746.000753032, 'ymin': 4020957.451106308, 'xmax': -13014666.49652086, 'ymax': 4051532.26242039} # print printed_file_url = wm.print(file_format='JPG', extent=redlands_extent) printed_file2_url = wm2.print(file_format='PNG32', extent=redlands_extent) # Display the result in a notebook: from IPython.display import Image Image(printed_file_url) # Download file to disk import requests with requests.get(printed_file_url) as resp: with open('./output_file.png', 'wb') as file_handle: file_handle.write(resp.content)
-
remove_layer
(layer)¶ Removes the specified layer from the web map. You can get the list of layers in map using the ‘layers’ property and pass one of those layers to this method for removal form the map.
Argument
Description
layer
Required object. Pass the layer that needs to be removed from the map. You can get the list of layers in the map by calling the layers property.
-
remove_table
(table)¶ Removes the specified table from the web map. You can get the list of tables in map using the ‘tables’ property and pass one of those tables to this method for removal form the map.
Argument
Description
table
Required object. Pass the table that needs to be removed from the map. You can get the list of tables in the map by calling the tables property.
-
save
(item_properties, thumbnail=None, metadata=None, owner=None, folder=None)¶ Save the WebMap object into a new web map Item in your GIS.
Note
If you started out with a fresh WebMap object, use this method to save it as a the web map item in your GIS.
If you started with a WebMap object from an existing web map item, calling this method will create a new item with your changes. If you want to update the existing web map item with your changes, call the update() method instead.
Argument
Description
item_properties
Required dictionary. See table below for the keys and values.
thumbnail
Optional string. Either a path or URL to a thumbnail image.
metadata
Optional string. Either a path or URL to the metadata.
owner
Optional string. Defaults to the logged in user.
folder
Optional string. Name of the folder into which the web map should be saved.
Key:Value Dictionary Options for Argument item_properties
Key
Value
typeKeywords
Optional string. Provide a lists all sub-types, see URL 1 below for valid values.
description
Optional string. Description of the item.
extent
Optional dict, string, or array. The extent of the item.
title
Optional string. Name label of the item.
tags
Optional string. Tags listed as comma-separated values, or a list of strings. Used for searches on items.
snippet
Optional string. Provide a short summary (limit to max 250 characters) of the what the item is.
accessInformation
Optional string. Information on the source of the content.
licenseInfo
Optional string. Any license information or restrictions regarding the content.
culture
Optional string. Locale, country and language information.
access
Optional string. Valid values are private, shared, org, or public.
commentsEnabled
Optional boolean. Default is true, controls whether comments are allowed (true) or not allowed (false).
culture
Optional string. Language and country information.
The above are the most common item properties (metadata) that you set. To get a complete list, see https://developers.arcgis.com/rest/users-groups-and-items/common-parameters.htm#ESRI_SECTION1_1FFBA7FE775B4BDA8D97524A6B9F7C98
- Returns
Item object corresponding to the new web map Item created.
# USAGE EXAMPLE 1: Save a WebMap object into a new web map item from arcgis.gis import GIS from arcgis.mapping import WebMap # log into your GIS gis = GIS(url, username, password) # compose web map by adding, removing, editing layers and basemaps wm = WebMap() # new web map wm.add_layer(...) # add some layers # save the web map webmap_item_properties = {'title':'Ebola incidents and facilities', 'snippet':'Map created using Python API showing locations of Ebola treatment centers', 'tags':['automation', 'ebola', 'world health', 'python'], 'extent': {'xmin': -122.68, 'ymin': 45.53, 'xmax': -122.45, 'ymax': 45.6, 'spatialReference': {'wkid': 4326}}} new_wm_item = wm.save(webmap_item_properties, thumbnail='./webmap_thumbnail.png') # to visit the web map using a browser print(new_wm_item.homepage) >> 'https://your portal url.com/webadaptor/item.html?id=1234abcd...'
-
property
scale_bar
¶ - Returns
Scale bar from (“none”, “ruler”, “scale”)
-
property
search
¶ - Returns
True if search is enabled for dashboard widget.
-
property
tables
¶ Tables in the web map
- Returns
List of Tables as dictionaries
wm = WebMap() table = Table('https://some-url.com/') wm.add_layer(table) wm.tables >> [{"id": "fZvgsrA68ElmNajAZl3sOMSPG3iTnL", "title": "change_table", "url": "https://some-url.com/", "popupInfo": { ...
-
update
(item_properties=None, thumbnail=None, metadata=None)¶ Updates the web map item in your GIS with the changes you made to the WebMap object. In addition, you can update other item properties, thumbnail and metadata.
Note
If you started with a WebMap object from an existing web map item, calling this method will update the item with your changes.
If you started out with a fresh WebMap object (without a web map item), calling this method will raise a RuntimeError exception. If you want to save the WebMap object into a new web map item, call the save() method instead.
For item_properties, pass in arguments for the properties you want to be updated. All other properties will be untouched. For example, if you want to update only the item’s description, then only provide the description argument in item_properties.
Argument
Description
item_properties
Optional dictionary. See table below for the keys and values.
thumbnail
Optional string. Either a path or URL to a thumbnail image.
metadata
Optional string. Either a path or URL to the metadata.
Key:Value Dictionary Options for Argument item_properties
Key
Value
typeKeywords
Optional string. Provide a lists all sub-types, see URL 1 below for valid values.
description
Optional string. Description of the item.
title
Optional string. Name label of the item.
tags
Optional string. Tags listed as comma-separated values, or a list of strings. Used for searches on items.
snippet
Optional string. Provide a short summary (limit to max 250 characters) of the what the item is.
accessInformation
Optional string. Information on the source of the content.
licenseInfo
Optional string. Any license information or restrictions regarding the content.
culture
Optional string. Locale, country and language information.
access
Optional string. Valid values are private, shared, org, or public.
commentsEnabled
Optional boolean. Default is true, controls whether comments are allowed (true) or not allowed (false).
The above are the most common item properties (metadata) that you set. To get a complete list, see https://developers.arcgis.com/rest/users-groups-and-items/common-parameters.htm#ESRI_SECTION1_1FFBA7FE775B4BDA8D97524A6B9F7C98
- Returns
A boolean indicating success (True) or failure (False).
# USAGE EXAMPLE 1: Update an existing web map from arcgis.gis import GIS from arcgis.mapping import WebMap # log into your GIS gis = GIS(url, username, password) # edit web map by adding, removing, editing layers and basemaps wm = WebMap() # new web map wm.add_layer(...) # add some layers # save the web map webmap_item_properties = {'title':'Ebola incidents and facilities', 'snippet':'Map created using Python API showing locations of Ebola treatment centers', 'tags':['automation', 'ebola', 'world health', 'python']} new_wm_item = wm.save(webmap_item_properties, thumbnail='./webmap_thumbnail.png') # to visit the web map using a browser print(new_wm_item.homepage) >> 'https://your portal url.com/webadaptor/item.html?id=1234abcd...'
-
property
width
¶ - Returns
Width of the widget
-
property
zoom
¶ - Returns
zoom enabled or disabled for dashboard widget.
-
OfflineMapAreaManager¶
-
class
arcgis.mapping.
OfflineMapAreaManager
(item, gis)¶ Bases:
object
Helper class to manage offline map areas attached to a web map item. Users should not instantiate this class directly, instead, should access the methods exposed by accessing the offline_areas property on the WebMap object.
-
create
(area, item_properties=None, folder=None, min_scale=None, max_scale=None, layers_to_ignore=None, refresh_schedule='Never', refresh_rates=None, enable_updates=False, ignore_layers=None, tile_services=None, future=False)¶ Create offline map area items and packages for ArcGIS Runtime powered applications. This method creates two different types of items. It first creates ‘Map Area’ items for the specified extent or bookmark. Next it creates one or more map area packages corresponding to each layer type in the extent.
Note
There can be only 1 map area item for an extent or bookmark.
You need to be the owner of the web map or an administrator of your GIS.
Argument
Description
area
Required object. Bookmark or extent. Specify as either:
- bookmark name
WebMap.definition.bookmarks returns list of bookmarks.
- list of coordinate pairs:
[[‘xmin’, ‘ymin’], [‘xmax’, ‘ymax’]]
- dictionary:
{‘xmin’: <value>, ‘ymin’: <value>, ‘xmax’: <value>, ‘ymax’: <value>, ‘spatialReference’ : {‘wkid’ : <value>}}
If spatial reference is not specified, it is assumed ‘wkid’: 4326.
item_properties
Required dictionary. See table below for the keys and values.
folder
Optional string. Specify a folder name if you want the offline map area item and the packages to be created inside a folder.
min_scale
Optional number. Specify the minimum scale to cache tile and vector tile layers. When zoomed out beyond this scale, cached layers would not display.
max_scale
Optional number. Specify the maximum scale to cache tile and vector tile layers. When zoomed in beyond this scale, cached layers would not display.
layers_to_ignore
Optional List of layer objects to exclude when creating offline packages. You can get the list of layers in a web map by calling the layers property on the WebMap object.
refresh_schedule
Optional string. Allows for the scheduling of refreshes at given times.
The following are valid variables:
Never - never refreshes the offline package (default)
Daily - refreshes everyday
Weekly - refreshes once a week
Monthly - refreshes once a month
refresh_rates
Optional dict. This parameter allows for the customization of the scheduler. The dictionary accepts the following:
- {
“hour” : 1 “minute” = 0 “nthday” = 3 “day_of_week” = 0
}
hour - a value between 0-23 (integers)
minute a value between 0-60 (integers)
nthday - this is used for monthly only. This say the refresh will occur on the ‘x’ day of the month.
day_of_week - a value between 0-6 where 0 is Sunday and 6 is Saturday.
Example Daily:
- {
“hour”: 10, “minute” : 30
}
This means every day at 10:30 AM UTC
Example Weekly:
- {
“hour” : 23, “minute” : 59, “day_of_week” : 4
}
This means every Wednesday at 11:59 PM UTC
enable_updates
Optional Boolean. Allows for the updating of the layers.
ignore_layers
Optional List. A list of individual layers, specified with their service URLs, in the map to ignore. The task generates packages for all map layers by default.
Example:
tile_services
Optional List. An array of JSON objects that contains additional export tiles enabled tile services for which tile packages (.tpk or .vtpk) need to be created. Each tile service is specified with its URL and desired level of details.
Example:
- [
- {
“url”: “https://tiledbasemaps.arcgis.com/arcgis/rest/services/World_Imagery/MapServer”, “levels”: “17,18,19”
}
]
Hint: Your min_scale is always bigger in value than your max_scale
Key:Value Dictionary Options for Argument item_properties
Key
Value
description
Optional string. Description of the item.
title
Optional string. Name label of the item.
tags
Optional string. Tags listed as comma-separated values, or a list of strings. Used for searches on items.
snippet
Optional string. Provide a short summary (limit to max 250 characters) of the what the item is.
- Returns
Item object for the offline map area item that was created. If Future==True, then the result is a PackageJob
USAGE EXAMPLE: Creating offline map areas wm = WebMap(wm_item) # create offline areas ignoring a layer and for certain min, max scales for other layers item_prop = {'title': 'Clear lake hyperspectral field campaign', 'snippet': 'Offline package for field data collection using spectro-radiometer', 'tags': ['python api', 'in-situ data', 'field data collection']} aviris_layer = wm.layers[-1] north_bed = wm.definition.bookmarks[-1]['name'] wm.offline_areas.create(area=north_bed, item_properties=item_prop, folder='clear_lake', min_scale=9000, max_scale=4500, layers_to_ignore=[aviris_layer])
Note
This method executes silently. To view informative status messages, set the verbosity environment variable as shown below:
USAGE EXAMPLE: setting verbosity from arcgis import env env.verbose = True
-
list
()¶ Returns a list of Map Area items related to the current WebMap object.
Note
Map Area items and the corresponding offline packages cached for each share a relationship of type ‘Area2Package’. You can use this relationship to get the list of package items cached for a particular Map Area item. Refer to the Python snippet below for the steps:
USAGE EXAMPLE: Finding packages cached for a Map Area item from arcgis.mapping import WebMap wm = WebMap(a_web_map_item_object) all_map_areas = wm.offline_areas.list() # get all the offline areas for that web map area1 = all_map_areas[0] area1_packages = area1.related_items('Area2Package','forward') for pkg in area1_packages: print(pkg.homepage) # get the homepage url for each package item.
- Returns
List of Map Area items related to the current WebMap object
-
modify_refresh_schedule
(item, refresh_schedule=None, refresh_rates=None)¶ Modifies an Existing Package’s Refresh Schedule for offline packages.
Argument
Description
item
Required Item. This is the Offline Package to update the refresh schedule.
refresh_schedule
Optional String. This is the rate of refreshing.
The following are valid variables:
Never - never refreshes the offline package (default)
Daily - refreshes everyday
Weekly - refreshes once a week
Monthly - refreshes once a month
refresh_rates
Optional dict. This parameter allows for the customization of the scheduler. Note all time is in UTC.
The dictionary accepts the following:
- {
“hour” : 1 “minute” = 0 “nthday” = 3 “day_of_week” = 0
}
hour - a value between 0-23 (integers)
minute a value between 0-60 (integers)
nthday - this is used for monthly only. This say the refresh will occur on the ‘x’ day of the month.
day_of_week - a value between 0-6 where 0 is Sunday and 6 is Saturday.
Example Daily:
- {
“hour”: 10, “minute” : 30
}
This means every day at 10:30 AM UTC
Example Weekly:
- {
“hour” : 23, “minute” : 59, “day_of_week” : 4
}
This means every Wednesday at 11:59 PM UTC
- Returns
boolean
## Updates Offline Package Building Everyday at 10:30 AM UTC
gis = GIS(profile='owner_profile') item = gis.content.get('9b93887c640a4c278765982aa2ec999c') oa = wm.offline_areas.modify_refresh_schedule(item.id, 'daily', {'hour' : 10, 'minute' : 30})
-
property
offline_properties
¶ This property allows users to configure the offline properties for a webmap. The offline_properties allows for the definition of how available offline editing, basemap, and read-only layers behave in the web map application.
Argument
Description
values
Required Dict. The key/value object that defines the offline application properties.
The dictionary supports the following keys in the dictionary
Key
Values
download
When editing layers, the edits are always sent to the server. This string value indicates which data is retrieved. For example, none indicates that only the schema is written since neither the features nor attachments are retrieved. For a full sync without downloading attachments, indicate features. Lastly, the default behavior is to have a full sync using features_and_attachments where both features and attachments are retrieved.
If property is present, must be one of the following values:
Allowed Values: [features, features_and_attachments, None]
sync
sync applies to editing layers only. This string value indicates how the data is synced.
Allowed Values:
sync_features_and_attachments - bidirectional sync sync_features_upload_attachments - bidirection sync for feaures but upload only for attachments upload_features_and_attachments - upload only for both features and attachments (initial replica is just a schema)
reference_basemap
The filename of a basemap that has been copied to a mobile device. This can be used instead of the default basemap for the map to reduce downloads.
get_attachments
Boolean value that indicates whether to include attachments with the read-only data.
- Returns
Dictionary
-
update
(offline_map_area_items=None, future=False)¶ Refreshes existing map area packages associated with the list of map area items specified. This process updates the packages with changes made on the source data since the last time those packages were created or refreshed.
Note
Offline map area functionality is only available if your GIS is ArcGIS Online.
You need to be the owner of the web map or an administrator of your GIS.
Argument
Description
offline_map_area_items
Optional list. Specify one or more Map Area items for which the packages need to be refreshed. If not specified, this method updates all the packages associated with all the map area items of the web map.
To get the list of Map Area items related to the WebMap object, call the list() method.
future
Optional Boolean.
- Returns
Dictionary containing update status.
Note
This method executes silently. To view informative status messages, set the verbosity environment variable as shown below:
USAGE EXAMPLE: setting verbosity from arcgis import env env.verbose = True
-
PackagingJob¶
-
class
arcgis.mapping.
PackagingJob
(future, notify=False)¶ Bases:
object
Represents a Single Packaging Job.
Argument
Description
future
Required ccurrent.futures.Future. The async object created by the geoprocessing (GP) task.
notify
Optional Boolean. When set to True, a message will inform the user that the geoprocessing task has completed. The default is False.
-
cancel
()¶ Attempt to cancel the call. If the call is currently being executed or finished running and cannot be cancelled then the method will return False, otherwise the call will be cancelled and the method will return True.
- Returns
boolean
-
cancelled
()¶ Return True if the call was successfully cancelled.
- Returns
boolean
-
done
()¶ Return True if the call was successfully cancelled or finished running.
- Returns
boolean
-
property
ellapse_time
¶ Returns the Ellapse Time for the Job
-
result
()¶ Return the value returned by the call. If the call hasn’t yet completed then this method will wait.
- Returns
object
-
running
()¶ Return True if the call is currently being executed and cannot be cancelled.
- Returns
boolean
-
property
status
¶ returns the GP status
- Returns
String
-
WebScene¶
-
class
arcgis.mapping.
WebScene
(websceneitem)¶ Bases:
collections.OrderedDict
Represents a web scene and provides access to its basemaps and operational layers as well as functionality to visualize and interact with them.
If you would like more robust webscene authoring functionality, consider using the
MapView
class. You need to be using a Jupyter environment for the MapView class to function properly, but you can make copies of WebScenes, add layers using a simple add_layer() call, adjust the basemaps, save to new webscenes, and more.-
update
([E, ]**F) → None. Update D from dict/iterable E and F.¶ If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
-
MapImageLayer¶
-
class
arcgis.mapping.
MapImageLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
MapImageLayer allows you to display and analyze data from sublayers defined in a map service, exporting images instead of features. Map service images are dynamically generated on the server based on a request, which includes an LOD (level of detail), a bounding box, dpi, spatial reference and other options. The exported image is of the entire map extent specified.
MapImageLayer does not display tiled images. To display tiled map service layers, see TileLayer.
-
create_dynamic_layer
(layer)¶ A dynamic layer / table method 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 by supportsDynamicLayers on the map image layer properties.
Argument
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
arcgis.features.FeatureLayer or None (if not enabled)
-
estimate_export_tiles_size
(export_by, levels, tile_package=False, export_extent='DEFAULTEXTENT', area_of_interest=None, asynchronous=True, **kwargs)¶ The estimate_export_tiles_size method is an asynchronous task that allows estimation of the size of the tile package or the cache data set that you download using the Export Tiles operation. This operation can also be used to estimate the tile count in a tile package and determine if it will exceced the maxExportTileCount limit set by the administrator of the service. The result of this operation is Map Service Job. This job response contains reference to Map Service Result resource that returns the total size of the cache to be exported (in bytes) and the number of tiles that will be exported.
Argument
Description
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
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
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
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
optiona 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, bbox_sr=None, size='600, 550', dpi=200, image_sr=None, image_format='png', layer_defs=None, layers=None, transparent=False, time_value=None, time_options=None, dynamic_layers=None, gdb_version=None, scale=None, rotation=None, transformation=None, map_range_values=None, layer_range_values=None, layer_parameter=None, f='json', save_folder=None, save_file=None, **kwargs)¶ The export operation 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.
- Returns
string, image of the map.
-
export_tiles
(levels, export_by='LevelID', tile_package=True, export_extent=None, optimize_for_size=True, compression=75, area_of_interest=None, asynchronous=False, storage_format=None, **kwargs)¶ The exportTiles operation 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 a Map Service that allows clients to export cache tiles. The result of this operation is Map Service Job. This job response contains a reference to the Map Service Result resource, which returns a URL to the resulting tile package (.tpk) or a cache raster dataset. exportTiles can 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 enable Allow Clients to Export Cache Tiles in the advanced caching page of the Service Editor. You can also specify the maximum tiles clients will be allowed to download. 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=true and maxExportTilesCount=100000.
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/submitJob operation is deprecated. You can provide arguments to the exportTiles operation as defined in the following parameters table:
Argument
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 defaut is ‘LevelID’. Values: LevelID | Resolution | Scale
tile_package
optiona 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
path to download file is asynchronous is False. If True, a dictionary is returned.
-
find
(search_text, layers, contains=True, search_fields=None, sr=None, layer_defs=None, return_geometry=True, max_offset=None, precision=None, dynamic_layers=None, return_z=False, return_m=False, gdb_version=None, return_unformatted=False, return_field_name=False, transformations=None, map_range_values=None, layer_range_values=None, layer_parameters=None, **kwargs)¶ performs the map service find operation
Argument
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 resultset 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 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 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_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
dictionary
-
classmethod
fromitem
(item)¶ Returns the layer at the specified index from a layer item.
Argument
Description
item
Required string. An item ID representing a layer.
index
Optional int. The index of the layer amongst the item’s layers
- Returns
The layer at the specified index.
-
generate_kml
(save_location, name, layers, options='composite')¶ The generateKml operation is performed on a map service resource. The result of this operation is a KML document wrapped in a KMZ file. The document contains a network link to the KML Service endpoint with properties and parameters you specify.
Argument
Description
save_location
required string. Save folder.
name
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
string to file path
-
identify
(geometry, map_extent, image_display, geometry_type='Point', sr=None, layer_defs=None, time_value=None, time_options=None, layers='all', tolerance=None, return_geometry=True, max_offset=None, precision=4, dynamic_layers=None, return_z=False, return_m=False, gdb_version=None, return_unformatted=False, return_field_name=False, transformations=None, map_range_values=None, layer_range_values=None, layer_parameters=None, **kwargs)¶ The identify operation is performed on a map service resource to discover features at a geographic location. The result of this operation is an identify results resource. Each identified result includes its name, layer ID, layer name, geometry and geometry type, and other attributes of that result as name-value pairs.
- Returns
dictionary
-
property
item_info
¶ returns the service’s item’s infomation
-
property
kml
¶ returns the KML file for the layer
-
property
legend
¶ The legend resource 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.
The legend symbols include the base64 encoded imageData as well as a url that could be used to retrieve the image from the server.
-
property
manager
¶
-
property
metadata
¶ returns the service’s XML metadata file
-
thumbnail
(out_path=None)¶ if present, this operation will download the image to local disk
-
MapServiceLayer¶
-
class
arcgis.mapping.
MapServiceLayer
(url, gis=None, container=None, dynamic_layer=None)¶ Bases:
arcgis.gis.Layer
Factory that generates the Map Service Layers
Argument
Description
url
Required string, specify the url ending in /MapServer/<index>
gis
Optional
GIS
object. If not specified, the active GIS connection is used.# USAGE EXAMPLE 1: Instantiating a Map Service Layer object from arcgis.mapping import MapServiceLayer ms_layer = MapServiceLayer(url='https://your_portal.com/arcgis/rest/services/service_name/MapServer/0') type(ms_layer) >> arcgis.mapping._types.MapTable print(ms_layer.properties.name) >> 'pipe_properties'
MapFeatureLayer¶
-
class
arcgis.mapping.
MapFeatureLayer
(url, gis=None, container=None, dynamic_layer=None)¶ Bases:
arcgis.gis.Layer
Map Feature Layers can be added to and visualized using maps.
Map Feature Layers are created by publishing feature data to a GIS, and are exposed as a broader resource (Item) in the GIS. MapFeatureLayer objects can be obtained through the layers attribute on map image service Items in the GIS.
-
property
attachements
¶ Provides a manager to work with attachments if the MapFeatureLayer supports this functionality
-
property
container
¶ The MapImageLayer to which this layer belongs.
-
export_attachments
(output_folder, label_field=None)¶ Exports attachments from the map feature layer in Imagenet format using the output_label_field.
Argument
Description
output_folder
Required. Output folder where the attachments will be stored.
label_field
Optional. Field which contains the label/category of each feature. If None, a default folder is created.
-
classmethod
fromitem
(item, layer_id=0)¶ Creates a map feature layer from a GIS Item. The type of item should be a ‘Map Image Layer’. The layer_id is the id of the layer in Map Service’s layers.
-
generate_renderer
(definition, where=None)¶ This operation groups data using the supplied definition (classification definition) and an optional where clause. The result is a renderer object. Use baseSymbol and colorRamp to define the symbols assigned to each class. If the operation is performed on a table, the result is a renderer object containing the data classes and no symbols.
Argument
Description
definition
required dict. The definition using the renderer that is generated. Use either class breaks or unique value classification definitions. See: https://resources.arcgis.com/en/help/rest/apiref/ms_classification.html
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
dictionary
-
get_html_popup
(oid)¶ The htmlPopup resource provides details about the HTML pop-up authored by the user using ArcGIS Pro or ArcGIS Desktop.
Argument
Description
oid
Optional string. Object id of the feature to get the HTML popup.
- Returns
string
-
get_unique_values
(attribute, query_string='1=1')¶ Return a list of unique values for a given attribute
Argument
Description
attribute
Required string. The map feature layer attribute to query.
query_string
Optional string. SQL Query that will be used to filter attributes before unique values are returned. ex. “name_2 like ‘%K%’”
-
query
(where='1=1', text=None, out_fields='*', time_filter=None, geometry_filter=None, return_geometry=True, return_count_only=False, return_ids_only=False, return_distinct_values=False, return_extent_only=False, group_by_fields_for_statistics=None, statistic_filter=None, result_offset=None, result_record_count=None, object_ids=None, distance=None, units=None, max_allowable_offset=None, out_sr=None, geometry_precision=None, gdb_version=None, order_by_fields=None, out_statistics=None, return_z=False, return_m=False, multipatch_option=None, quantization_parameters=None, return_centroid=False, return_all_records=True, result_type=None, historic_moment=None, sql_format=None, return_true_curves=False, return_exceeded_limit_features=None, as_df=False, datum_transformation=None, range_values=None, parameter_values=None, **kwargs)¶ Queries a map feature layer based on a sql statement
Argument
Description
where
Optional string. The default is 1=1. The selection sql statement.
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 either as a List of field names or as 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. Values: esriSRUnit_Meter | esriSRUnit_StatuteMile |
esriSRUnit_Foot | esriSRUnit_Kilometer | esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile
time_filter
Optional list. The format is of [<startTime>, <endTime>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp in milliseconds
geometry_filter
Optional from arcgis.geometry.filter. 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. The max_allowable_offset is in the units of out_sr. If out_sr is not specified, max_allowable_offset is assumed to be in the unit 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 this is 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 the 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 feature set.
return_count_only
Optional boolean. If true, the response only includes the count (number of features/records) that would be returned by a query. Otherwise, the response is a feature set. The default is false. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.
return_extent_only
Optional boolean. If true, the response only includes the extent of the features that would be returned by 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. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER
group_by_fields_for_statistics
Optional string. One or more field names on which the values need to be grouped for calculating the statistics. example: STATE_NAME, GENDER
out_statistics
Optional string. The definitions for one or more field-based statistics to be calculated.
Syntax:
- [
- {
“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_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 + 1th). This option is ignored if return_all_records is True (i.e. by default).
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 max_record_count property. This option is ignored if return_all_records is True (i.e. by default).
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 return_all_records is True. Also, if return_count_only, return_ids_only, or return_extent_only are True, this parameter will be ignored.
result_type
Optional string. The result_type parameter can be used to control the number of features returned by the query operation. Values: None | standard | tile
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 resource.
If historic_moment is not specified, the query will apply to the current features.
sql_format
Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native
return_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 ‘exceededTransferLimit’: True.
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.
Examples
Inputs
Description
WKID
Integer. Ex: datum_transformation=4326
WKT
Dict. Ex: datum_transformation={“wkt”: “<WKT>”}
Composite
Dict. Ex: datum_transformation=```{‘geoTransforms’:[{‘wkid’:<id>,’forward’:<true|false>},{‘wkt’:’<WKT>’,’forward’:<True|False>}]}```
range_values
Optional List. Allows you to filter features from the layer that are within the specified range instant or extent.
- Syntax
- [
- {
“name”: “range name”, “value”: <value> or [ <value1>, <value2> ] # single value or a value-range
# None is allowed in value-range case – that means infinity # e.g. [None, 1500] means all features with values <= 1500 # [1000, None] means all features with values >= 1000
}, {
“name”: “range name 2”, “value”: <value> or [ <value3>, <value4> ]
}
}
]
parameter_values
Optional Dict. Allows you to filter the features 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 parameterInfos at the layer resources for the available parameterized filters, their default values and expected data type.
kwargs
Optional dict. Optional parameters that can be passed to the Query function. This will allow users to pass additional parameters not explicitly implemented on the function. A complete list of functions available is documented on the Query REST API.
- Returns
A FeatureSet containing the features matching the query unless another return type is specified, such as count
The Query operation is performed on a feature service layer resource. The result of this operation are feature sets grouped by source layer/table object IDs. Each feature set contains Feature objects including the values for the fields requested by the user. 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.
Argument
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
Required string. the list of 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/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_curves
Optional boolean. Optional parameter that is false by default. When set to true, returns true curves in output geometries; otherwise, curves are converted to densified polylines or polygons.
- Returns
dict
-
property
renderer
¶ Get/Set the Renderer of the Map Feature Layer. This overrides the default symbology when displaying it on a webmap.
- Returns
InsensitiveDict
-
property
time_filter
¶ Starting at Enterprise 10.7.1+, instead of querying time-enabled map service layers or time-enabled feature service layers, a time filter can be specified. Time can be filtered as a single instant or by separating the two ends of a time extent with a comma.
Input
Description
value
Required Datetime/List Datetime. This is a single or list of start/stop date.
- Returns
String of datetime values as milliseconds from epoch
-
property
MapRasterLayer¶
-
class
arcgis.mapping.
MapRasterLayer
(url, gis=None, container=None, dynamic_layer=None)¶ Bases:
arcgis.mapping._msl.layer.MapFeatureLayer
A Map Raster Layer represents a geo-referenced image hosted in a Map Service.
MapTable¶
-
class
arcgis.mapping.
MapTable
(url, gis=None, container=None, dynamic_layer=None)¶ Bases:
arcgis.mapping._msl.layer.MapFeatureLayer
Tables represent entity classes with uniform properties. In addition to working with “entities with location” as features, the GIS can also work with non-spatial entities as rows in tables.
Working with tables is similar to working with map feature layers, except that the rows (Features) in a table do not have a geometry, and tables ignore any geometry related operation.
-
classmethod
fromitem
(item, table_id=0)¶ Creates a Table from a GIS Item. The type of item should be a ‘Map Image Service’. The layer_id is the id of the layer.
-
query
(where='1=1', out_fields='*', time_filter=None, return_count_only=False, return_ids_only=False, return_distinct_values=False, group_by_fields_for_statistics=None, statistic_filter=None, result_offset=None, result_record_count=None, object_ids=None, gdb_version=None, order_by_fields=None, out_statistics=None, return_all_records=True, historic_moment=None, sql_format=None, return_exceeded_limit_features=None, as_df=False, range_values=None, parameter_values=None, **kwargs)¶ Queries a Table Layer based on a set of criteria.
Argument
Description
where
Optional string. The default is 1=1. The selection sql statement.
out_fields
Optional List of field names to return. Field names can be specified either as a List of field names or as 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.
time_filter
Optional list. The format is of [<startTime>, <endTime>] using datetime.date, datetime.datetime or timestamp in milliseconds. Syntax: time_filter=[<startTime>, <endTime>] ; specified as
datetime.date, datetime.datetime or timestamp in milliseconds
gdb_version
Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If this is 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 the 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 feature set.
return_count_only
Optional boolean. If true, the response only includes the count (number of features/records) that would be returned by a query. Otherwise, the response is a feature set. The default is false. This option supersedes the returnIdsOnly parameter. If returnCountOnly = true, the response will return both the count and the extent.
order_by_fields
Optional string. One or more field names on which the features/records need to be ordered. Use ASC or DESC for ascending or descending, respectively, following every field to control the ordering. example: STATE_NAME ASC, RACE DESC, GENDER
group_by_fields_for_statistics
Optional string. One or more field names on which the values need to be grouped for calculating the statistics. example: STATE_NAME, GENDER
out_statistics
Optional string. The definitions for one or more field-based statistics to be calculated.
Syntax:
- [
- {
“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”
}
]
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 + 1th). This option is ignored if return_all_records is True (i.e. by default).
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 max_record_count property. This option is ignored if return_all_records is True (i.e. by default).
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 return_all_records is True. Also, if return_count_only, return_ids_only, or return_extent_only are True, this parameter will be ignored.
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 resource.
If historic_moment is not specified, the query will apply to the current features.
sql_format
Optional string. The sql_format parameter can be either standard SQL92 standard or it can use the native SQL of the underlying datastore native. The default is none which means the sql_format depends on useStandardizedQuery parameter. Values: none | standard | native
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 ‘exceededTransferLimit’: True.
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.
range_values
Optional List. Allows you to filter features from the layer that are within the specified range instant or extent.
- Syntax
- [
- {
“name”: “range name”, “value”: <value> or [ <value1>, <value2> ] # single value or a value-range
# None is allowed in value-range case – that means infinity # e.g. [None, 1500] means all features with values <= 1500 # [1000, None] means all features with values >= 1000
}, {
“name”: “range name 2”, “value”: <value> or [ <value3>, <value4> ]
}
}
]
parameter_values
Optional Dict. Allows you to filter the features 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 parameterInfos at the layer resources for the available parameterized filters, their default values and expected data type.
kwargs
Optional dict. Optional parameters that can be passed to the Query function. This will allow users to pass additional parameters not explicitly implemented on the function. A complete list of functions available is documented on the Query REST API.
- Returns
A FeatureSet or Panda’s DataFrame containing the features matching the query unless another return type is specified, such as count
-
classmethod
MapImageLayerManager¶
-
class
arcgis.mapping.
MapImageLayerManager
(url, gis=None, map_img_lyr=None)¶ Bases:
arcgis.gis._GISResource
allows administration (if access permits) of ArcGIS Online hosted map image layers. A map image layer offers access to map and layer content.
-
cancel_job
(job_id)¶ The cancel job 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.
- Inputs:
job_id - job id to cancel
-
delete_tiles
(levels, extent=None)¶ Deletes tiles for the current cache
Argument
Description
extent
optional dictionary, If specified, the tiles within this extent will be deleted or will be deleted based on the service’s full extent. Example: 6224324.092137296,487347.5253569535, 11473407.698535524,4239488.369818687 the minx, miny, maxx, maxy values or, {“xmin”:6224324.092137296,”ymin”:487347.5253569535, “xmax”:11473407.698535524,”ymax”:4239488.369818687, “spatialReference”:{“wkid”:102100}} the JSON representation of the Extent object.
levels
required string, The level to delete. Example, 0-5,10,11-20 or 1,2,3 or 0-5
- Returns
dictionary
-
edit_tile_service
(service_definition=None, min_scale=None, max_scale=None, source_item_id=None, export_tiles_allowed=False, max_export_tile_count=100000)¶ This operation updates a Tile Service’s properties
- Inputs:
service_definition - updates a service definition min_scale - sets the services minimum scale for caching max_scale - sets the service’s maximum scale for caching source_item_id - The Source Item ID is the GeoWarehouse Item ID of the map service export_tiles_allowed - sets the value to let users export tiles max_export_tile_count - sets the maximum amount of tiles to be exported
from a single call.
-
import_tiles
(item, levels=None, extent=None, merge=False, replace=False)¶ Argument
Description
item
Required ItemId or Item. The TPK file’s item id. This TPK file contains to-be-extracted bundle files which are then merged into an existing cache service.
levels
Optional String / List of integers, The level of details to update. Example: “1,2,10,20” or [1,2,10,20]
extent
Optional String / Dict. The area to update as Xmin, YMin, XMax, YMax example: “-100,-50,200,500” or {‘xmin’:100, ‘ymin’:200, ‘xmax’:105, ‘ymax’:205}
merge
Optional Boolean. Default is false and applicable 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. Default is false, applicable 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
Dict
-
job_statistics
(job_id)¶ Returns the job statistics for the given jobId
-
refresh
(service_definition=True)¶ The refresh operation refreshes a service, which clears the web server cache for the service.
-
property
rerun_job
¶ The rerun job operation 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.
Argument
Description
code
required string, parameter used to re-run a given jobs with a specific error code: ALL | ERROR | CANCELED
job_id
required string, job to reprocess
- Returns
boolean or dictionary
-
update_tiles
(levels=None, extent=None)¶ The starts tile generation for ArcGIS Online. The levels of detail and the extent are needed to determine the area where tiles need to be rebuilt.
..Note: This operation is for ArcGIS Online only.
Argument
Description
levels
Optional String / List of integers, The level of details to update. Example: “1,2,10,20” or [1,2,10,20]
extent
Optional String / Dict. The area to update as Xmin, YMin, XMax, YMax example: “-100,-50,200,500” or {‘xmin’:100, ‘ymin’:200, ‘xmax’:105, ‘ymax’:205}
- Returns
Dictionary. If the product is not ArcGIS Online tile service, the result will be None.
-
VectorTileLayer¶
-
class
arcgis.mapping.
VectorTileLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
-
classmethod
fromitem
(item)¶ Returns the layer at the specified index from a layer item.
Argument
Description
item
Required string. An item ID representing a layer.
index
Optional int. The index of the layer amongst the item’s layers
- Returns
The layer at the specified index.
-
property
info
¶ This returns relative paths to a list of resource files
-
property
styles
¶
-
tile_fonts
(fontstack, stack_range)¶ This resource returns glyphs in PBF format. The template url for this fonts resource is represented in Vector Tile Style resource.
-
tile_sprite
(out_format='sprite.json')¶ This resource returns sprite image and metadata
-
vector_tile
(level, row, column)¶ This resource represents a single vector tile for the map. 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.
-
classmethod
SceneLayer¶
-
class
arcgis.mapping.
SceneLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene layer. Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.PointCloudLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
BuildingLayer¶
-
class
arcgis.mapping.
BuildingLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene layer. Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.BuildingLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
IntegratedMeshLayer¶
-
class
arcgis.mapping.
IntegratedMeshLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene Point Cloud layer. Point Cloud layer are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
Object3DLayer¶
-
class
arcgis.mapping.
Object3DLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene Point Cloud layer. Point Cloud layer are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
Point3DLayer¶
-
class
arcgis.mapping.
Point3DLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene Point Cloud layer. Point Cloud layer are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.Point3DLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
PointCloudLayer¶
-
class
arcgis.mapping.
PointCloudLayer
(url, gis=None)¶ Bases:
arcgis.gis.Layer
Represents a Web scene Point Cloud layer. Point Cloud layer are cached web layers that are optimized for displaying a large amount of 2D and 3D features. You can use scene layers to represent 3D points, point clouds, 3D objects and integrated mesh layers.
Argument
Description
url
Required string, specify the url ending in /SceneServer/
gis
Optional GIS object. If not specified, the active GIS connection is used.
# USAGE EXAMPLE 1: Instantiating a SceneLayer object from arcgis.mapping import SceneLayer s_layer = SceneLayer(url='https://your_portal.com/arcgis/rest/services/service_name/SceneServer/') type(s_layer) >> arcgis.mapping._types.PointCloudLayer print(s_layer.properties.layers[0].name) >> 'your layer name'
export_map¶
-
arcgis.mapping.
export_map
(web_map_as_json: str = None, format: str = 'PDF', layout_template: str = 'MAP_ONLY', gis=None)¶ This function takes the state of the web map (for example, included services, layer visibility settings, client-side graphics, and so forth) and returns either (a) a page layout or (b) a map without page surrounds of the specified area of interest in raster or vector format. The input for this function is a piece of text in JavaScript object notation (JSON) format describing the layers, graphics, and other settings in the web map. The JSON must be structured according to the WebMap specification in the ArcGIS Help. This tool is shipped with ArcGIS Server to support web services for printing, including the preconfigured service named PrintingTools.
Parameters: ================== ==================================================================== Argument Description —————— ——————————————————————– web_map_as_json Web Map JSON along with export options. See
https://developers.arcgis.com/rest/services-reference/exportwebmap-specification.htm to understand how to structure this JSON
—————— ——————————————————————– format Format (str). Optional parameter. The format in which the map image
for printing will be delivered. The following strings are accepted. For example:PNG8 Choice list:[‘PDF’, ‘PNG32’, ‘PNG8’, ‘JPG’, ‘GIF’, ‘EPS’, ‘SVG’, ‘SVGZ’]
—————— ——————————————————————– layout_template Layout Template (str). Optional parameter. Either a name of a
template from the list or the keyword MAP_ONLY. When MAP_ONLY is chosen or an empty string is passed in, the output map does not contain any page layout surroundings (for example title, legends, scale bar, and so forth). Choice list:[‘A3 Landscape’, ‘A3 Portrait’, ‘A4 Landscape’, ‘A4 Portrait’, ‘Letter ANSI A Landscape’, ‘Letter ANSI A Portrait’, ‘Tabloid ANSI B Landscape’, ‘Tabloid ANSI B Portrait’, ‘MAP_ONLY’]. You can get the layouts configured with your GIS by calling the :meth:get_layout_templates<arcgis.mapping.get_layout_templates> function
—————— ——————————————————————– gis The :class:GIS<arcgis.gis.GIS> to use for printing. Optional
parameter. When not specified, the active GIS will be used.
get_layout_templates¶
-
arcgis.mapping.
get_layout_templates
(gis=None) → str¶ This function returns the content of the GIS’s layout templates formatted as dict.
Parameters:
gis: Optional, the GIS on which this tool runs. If not specified, the active GIS is used.
- Returns:
output_json - layout templates as Python dict
See https://utility.arcgisonline.com/arcgis/rest/directories/arcgisoutput/Utilities/PrintingTools_GPServer/Utilities_PrintingTools/GetLayoutTemplatesInfo.htm for additional help.
Symbology¶
Generates Symbol Types
-
arcgis.mapping.symbol.
create_symbol
(geometry_type, symbol_type=None, symbol_style=None, colors=None, **kwargs)¶ Generates a Symbol from a given set of Paramters
This method creates either a Picture, Text, Cartographic, or Simple Symbol based on a given set of parameters. Each symbol type has a specific set of parameters that are excepted. There is a simplified input definition similar to matplotlib.
Required Argument
Description
geometry_type
required string. This can be point, line, polygon, or multipoint. It helps to ensure that the symbol created will be supported by that geometry type.
Optional Argument
Description
symbol_type
optional string. This is the type of symbol the user needs to create. Valid inputs are: simple, picture, text, or carto. The default is simple.
symbol_style
optional string. This is the symbology used by the geometry. For example ‘s’ for a Line geometry is a solid line. And ‘-‘ is a dash line.
Point Symbols
‘o’ - Circle (default)
‘+’ - Cross
‘D’ - Diamond
‘s’ - Square
‘x’ - X
Polyline Symbols
‘s’ - Solid (default)
‘-‘ - Dash
‘-.’ - Dash Dot
‘-..’ - Dash Dot Dot
‘.’ - Dot
‘–’ - Long Dash
‘–.’ - Long Dash Dot
‘n’ - Null
‘s-‘ - Short Dash
‘s-.’ - Short Dash Dot
‘s-..’ - Short Dash Dot Dot
‘s.’ - Short Dot
Polygon Symbols
‘s’ - Solid Fill (default)
‘’ - Backward Diagonal
‘/’ - Forward Diagonal
‘|’ - Vertical Bar
‘-‘ - Horizontal Bar
‘x’ - Diagonal Cross
‘+’ - Cross
colors
optional string or list. This is the color scheme a user
can provide if the exact color is not needed, or a user can provide a list with the color defined as: [red, green blue, alpha]. The values red, green, blue are from 0-255 and alpha is a float value from 0 - 1. The default value is ‘jet’ color scheme.
cstep
optional integer. If provided, its the color location on the color scheme.
Simple Symbols
This is a list of optional parameters that can be given for point, line or polygon geometries.
Argument
Description
marker_size
optional float. Numeric size of the symbol given in points.
marker_angle
optional float. Numeric value used to rotate the symbol. The symbol is rotated counter-clockwise. For example, The following, angle=-30, in will create a symbol rotated -30 degrees counter-clockwise; that is, 30 degrees clockwise.
marker_xoffset
Numeric value indicating the offset on the x-axis in points.
marker_yoffset
Numeric value indicating the offset on the y-axis in points.
line_width
optional float. Numeric value indicating the width of the line in points
outline_style
Optional string. For polygon point, and line geometries , a customized outline type can be provided.
Allowed Styles:
‘s’ - Solid (default)
‘-‘ - Dash
‘-.’ - Dash Dot
‘-..’ - Dash Dot Dot
‘.’ - Dot
‘–’ - Long Dash
‘–.’ - Long Dash Dot
‘n’ - Null
‘s-‘ - Short Dash
‘s-.’ - Short Dash Dot
‘s-..’ - Short Dash Dot Dot
‘s.’ - Short Dot
outline_color
optional string or list. This is the same color as the colors property, but specifically applies to the outline_color.
Picture Symbol
This type of symbol only applies to Points, MultiPoints and Polygons.
Argument
Description
marker_angle
Numeric value that defines the number of degrees ranging from 0-360, that a marker symbol is rotated. The rotation is from East in a counter-clockwise direction where East is the 0 axis.
marker_xoffset
Numeric value indicating the offset on the x-axis in points.
marker_yoffset
Numeric value indicating the offset on the y-axis in points.
height
Numeric value used if needing to resize the symbol. Specify a value in points. If images are to be displayed in their original size, leave this blank.
width
Numeric value used if needing to resize the symbol. Specify a value in points. If images are to be displayed in their original size, leave this blank.
url
String value indicating the URL of the image. The URL should be relative if working with static layers. A full URL should be used for map service dynamic layers. A relative URL can be dereferenced by accessing the map layer image resource or the feature layer image resource.
image_data
String value indicating the base64 encoded data.
xscale
Numeric value indicating the scale factor in x direction.
yscale
Numeric value indicating the scale factor in y direction.
outline_color
optional string or list. This is the same color as the colors property, but specifically applies to the outline_color.
outline_style
Optional string. For polygon point, and line geometries , a customized outline type can be provided.
Allowed Styles:
‘s’ - Solid (default)
‘-‘ - Dash
‘-.’ - Dash Dot
‘-..’ - Dash Dot Dot
‘.’ - Dot
‘–’ - Long Dash
‘–.’ - Long Dash Dot
‘n’ - Null
‘s-‘ - Short Dash
‘s-.’ - Short Dash Dot
‘s-..’ - Short Dash Dot Dot
‘s.’ - Short Dot
outline_color
optional string or list. This is the same color as the colors property, but specifically applies to the outline_color.
line_width
optional float. Numeric value indicating the width of the line in points
Text Symbol
This type of symbol only applies to Points, MultiPoints and Polygons.
Argument
Description
font_decoration
The text decoration. Must be one of the following values: - line-through - underline - none
font_family
Optional string. The font family.
font_size
Optional float. The font size in points.
font_style
Optional string. The text style. - italic - normal - oblique
font_weight
Optional string. The text weight. Must be one of the following values: - bold - bolder - lighter - normal
background_color
optional string/list. Background color is represented as a four-element array or string of a color map.
halo_color
Optional string/list. Color of the halo around the text. The default is None.
halo_size
Optional integer/float. The point size of a halo around the text symbol.
horizontal_alignment
optional string. One of the following string values representing the horizontal alignment of the text. Must be one of the following values: - left - right - center - justify
kerning
optional boolean. Boolean value indicating whether to adjust the spacing between characters in the text string.
line_color
optional string/list. Outline color is represented as a four-element array or string of a color map.
line_width
optional integer/float. Outline size.
marker_angle
optional int. A numeric value that defines the number of degrees (0 to 360) that a text symbol is rotated. The rotation is from East in a counter-clockwise direction where East is the 0 axis.
marker_xoffset
optional int/float.Numeric value indicating the offset on the x-axis in points.
marker_yoffset
optional int/float.Numeric value indicating the offset on the x-axis in points.
right_to_left
optional boolean. Set to true if using Hebrew or Arabic fonts.
rotated
optional boolean. Boolean value indicating whether every character in the text string is rotated.
text
Required string. Text Value to display next to geometry.
vertical_alignment
Optional string. One of the following string values representing the vertical alignment of the text. Must be one of the following values: - top - bottom - middle - baseline
Cartographic Symbol
This type of symbol only applies to line geometries.
Argument
Description
line_width
optional float. Numeric value indicating the width of the line in points
cap
Optional string. The cap style.
join
Optional string. The join style.
miter_limit
Optional string. Size threshold for showing mitered line joins.
- Returns
Dictionary
-
arcgis.mapping.symbol.
display_colormaps
(colors=None)¶ Displays a visual colormaps in order to assist users in selecting a color scheme for the data they wish to display on a map, or in a web map.
This is a variation of http://matplotlib.org/examples/color/colormaps_reference.html
-
arcgis.mapping.symbol.
show_styles
(geometry_type)¶ Returns the available styles for a given geometry type as a Pandas dataframe
Renderers¶
generate_renderer¶
-
arcgis.mapping.renderer.
generate_renderer
(geometry_type, sdf_or_series=None, label=None, render_type=None, colors=None, **symbol_args)¶ Generates the Renderer JSON
Explicit Argument
Description
geometry_type
required string. The allowed values are: Point, Polyline, Polygon, or Raster. This required parameter is used to help ensure the requested renderer is valid for the specific type of geometry.
Geometry
Supported Renderer Types
Point
simple, unique, class breaks, heat map, temporal
Polyline
simple, unique, class break
Polygon
simple, unique, class break, dot density
Raster
stretched
The table above provides a quick summary based on the allowed renderer types based on the geometry.
sdf_or_series
optional SpatialDataFrame/Pandas Series/GeoSeries. The spatial dataset to render.
label
optional string. Name of the layer in the TOC/Legend
render_type
optional string. Determines the type of renderer to use for the provided dataset. The default is ‘s’ which is for simple renderers.
Allowed values:
‘s’ - is a simple renderer that uses one symbol only.
- ‘u’ - unique renderer symbolizes features based on one
or more matching string attributes.
- ‘u-a’ - unique renderer symbolizes features based on
an arcade expression.
- ‘c’ - A class breaks renderer symbolizes based on the
value of some numeric attribute.
- ‘h’ - heatmap renders point data into a raster
visualization that emphasizes areas of higher density or weighted values.
‘d’ - dot density renderer
colors
optional string/list. Color mapping. For simple renderer, just provide a string. For more robust renderers like unique renderer, a list can be given.
** Simple Renderer**
A simple renderer is a renderer that uses one symbol only.
Optional Argument
Description
symbol_type
optional string. This is the type of symbol the user needs to create. Valid inputs are: simple, picture, text, or carto. The default is simple.
symbol_style
optional string. This is the symbology used by the geometry. For example ‘s’ for a Line geometry is a solid line. And ‘-‘ is a dash line.
Point Symbols
‘o’ - Circle (default)
‘+’ - Cross
‘D’ - Diamond
‘s’ - Square
‘x’ - X
Polyline Symbols
‘s’ - Solid (default)
‘-‘ - Dash
‘-.’ - Dash Dot
‘-..’ - Dash Dot Dot
‘.’ - Dot
‘–’ - Long Dash
‘–.’ - Long Dash Dot
‘n’ - Null
‘s-‘ - Short Dash
‘s-.’ - Short Dash Dot
‘s-..’ - Short Dash Dot Dot
‘s.’ - Short Dot
Polygon Symbols
‘s’ - Solid Fill (default)
‘’ - Backward Diagonal
‘/’ - Forward Diagonal
‘|’ - Vertical Bar
‘-‘ - Horizontal Bar
‘x’ - Diagonal Cross
‘+’ - Cross
description
Description of the renderer.
rotation_expression
A constant value or an expression that derives the angle of rotation based on a feature attribute value. When an attribute name is specified, it’s enclosed in square brackets.
rotation_type
String value which controls the origin and direction of rotation on point features. If the rotationType is defined as arithmetic, the symbol is rotated from East in a counter-clockwise direction where East is the 0 degree axis. If the rotationType is defined as geographic, the symbol is rotated from North in a clockwise direction where North is the 0 degree axis.
Must be one of the following values:
arithmetic
geographic
visual_variables
An array of objects used to set rendering properties.
Heatmap Renderer
The HeatmapRenderer renders point data into a raster visualization that emphasizes areas of higher density or weighted values.
Optional Argument
Description
blur_radius
The radius (in pixels) of the circle over which the majority of each point’s value is spread.
field
This is optional as this renderer can be created if no field is specified. Each feature gets the same value/importance/weight or with a field where each feature is weighted by the field’s value.
max_intensity
The pixel intensity value which is assigned the final color in the color ramp.
min_intensity
The pixel intensity value which is assigned the initial color in the color ramp.
ratio
A number between 0-1. Describes what portion along the gradient the colorStop is added.
Predominance/Unique Renderer
This renderer symbolizes features based on one or more matching string attributes.
Optional Argument
Description
background_fill_symbol
A symbol used for polygon features as a background if the renderer uses point symbols, e.g. for bivariate types & size rendering. Only applicable to polygon layers. PictureFillSymbols can also be used outside of the Map Viewer for Size and Predominance and Size renderers.
default_label
Default label for the default symbol used to draw unspecified values.
default_symbol
Symbol used when a value cannot be matched.
field1, field2, field3
Attribute field renderer uses to match values.
field_delimiter
String inserted between the values if multiple attribute fields are specified.
rotation_expression
A constant value or an expression that derives the angle of rotation based on a feature attribute value. When an attribute name is specified, it’s enclosed in square brackets. Rotation is set using a visual variable of type rotation info with a specified field or value expression property.
rotation_type
String property which controls the origin and direction of rotation. If the rotation type is defined as arithmetic the symbol is rotated from East in a counter-clockwise direction where East is the 0 degree axis. If the rotation type is defined as geographic, the symbol is rotated from North in a clockwise direction where North is the 0 degree axis. Must be one of the following values:
arithmetic
geographic
arcade_expression
An Arcade expression evaluating to either a string or a number.
arcade_title
The title identifying and describing the associated Arcade expression as defined in the valueExpression property.
visual_variables
An array of objects used to set rendering properties.
unique_values
Optional list of dictionaries. If you want to define the unique values listed in the renderer, specify the list using this variable. The format of each unique value is as follows:
- {
“value” : <value>, “label” : <label value>, “description” : <optional text description>, “symbol” : {…symbol…}
}
Class Breaks Renderer
A class breaks renderer symbolizes based on the value of some numeric attribute.
Optional Argument
Description
background_fill_symbol
A symbol used for polygon features as a background if the renderer uses point symbols, e.g. for bivariate types & size rendering. Only applicable to polygon layers. PictureFillSymbols can also be used outside of the Map Viewer for Size and Predominance and Size renderers.
default_label
Default label for the default symbol used to draw unspecified values.
default_symbol
Symbol used when a value cannot be matched.
method
Determines the classification method that was used to generate class breaks.
Must be one of the following values:
esriClassifyDefinedInterval
esriClassifyEqualInterval
esriClassifyGeometricalInterval
esriClassifyNaturalBreaks
esriClassifyQuantile
esriClassifyStandardDeviation
esriClassifyManual
field
Attribute field used for renderer.
min_value
The minimum numeric data value needed to begin class breaks.
normalization_field
Used when normalizationType is field. The string value indicating the attribute field by which the data value is normalized.
normalization_total
Used when normalizationType is percent-of-total, this number property contains the total of all data values.
normalization_type
Determine how the data was normalized.
Must be one of the following values:
esriNormalizeByField
esriNormalizeByLog
esriNormalizeByPercentOfTotal
rotation_expression
A constant value or an expression that derives the angle of rotation based on a feature attribute value. When an attribute name is specified, it’s enclosed in square brackets.
rotation_type
A string property which controls the origin and direction of rotation. If the rotation_type is defined as arithmetic, the symbol is rotated from East in a couter-clockwise direction where East is the 0 degree axis. If the rotationType is defined as geographic, the symbol is rotated from North in a clockwise direction where North is the 0 degree axis.
Must be one of the following values:
arithmetic
geographic
arcade_expression
An Arcade expression evaluating to a number.
arcade_title
The title identifying and describing the associated Arcade expression as defined in the arcade_expression property.
visual_variables
An object used to set rendering options.
Dot Density Renderer
A class breaks renderer symbolizes based on the value of some numeric attribute.
Optional Argument
Description
attributes
Required List. The fields, labels and colors to add to the web map. The list consists of dictionarys with the following keys:
Argument
Description
field
Required String. Name of the dataset field
label
Required String. Descriptive name of the field.
color
Required List. A integer array consisting of R,G,B,A values
If the field name is not in the SeDF, then an error will be raised on renderering.
dot_value
Required Float. The unit value of what 1 dot equals.
ref_scale
Required Int. The reference scale of the dots.
unit
Required string. A label of the unit which each dot means.
blend_dots
Optional boolean. Allows for the dots to overlap.
size
Optional float. The size of the dot on the density map.
background
Optional List. A color background as a list of [r,g,b,a] values. The default is no background [0,0,0,0].
- Returns
dict
visual_variables¶
-
arcgis.mapping.renderer.
visual_variables
(geometry_type, sdf_or_list, **kwargs)¶ a function to create visual variables
This operation allows developers to take a deep dive into developing custom renderer. Here a user/developer can create transparancy, size information, and other rules to improve the overall feel and look of spatial information on a map.
Each type of information is detailed in the tables below.
arguements
description
ri_field
Attribute field used for setting the rotation of a symbol if no ri_expression is provided.
ri_type
Defines the origin and direction of rotation depending on how the angle of rotation was measured. Possible values are geographic which rotates the symbol from the north in a clockwise direction and arithmetic which rotates the symbol from the east in a counter-clockwise direction. Must be one of the following values:
geographic
arithmetic
ri_expression
An Arcade expression evaluating to a number.
ri_expression_title
The title identifying and describing the ri_expression