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.

Working with 2D Maps

WebMap

class arcgis.mapping.WebMap(**kwargs)

Bases: traitlets.traitlets.HasTraits, collections.OrderedDict

The WebMap class represents a web map and provides access to its basemaps and operational layers as well as functionality to visualize and interact with said basemaps and layers.

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.

Note

To learn more about web maps, see the Web maps page

Web maps can be used across ArcGIS apps because they adhere to the same web map specification. This provides the functionality to author web maps in one ArcGIS app (including the Python API) and view and modify them in another ArcGIS app.

Note

To learn more about the web map specification, refer to the Web Map Specification page

Parameter

Description

webmapitem

Optional Item object whose Item.type is Web Map.

Note

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
# USAGE EXAMPLE 2: Creating a new WebMap object

from arcgis.mapping import WebMap

# create a new WebMap object
wm = WebMap()
type(wm)
>> arcgis.mapping._types.WebMap

# explore the layers in this web map using the 'layers' property
wm.layers
>> []  # returns an empty list. You can add layers using the `add_layer()` method
add_layer(layer, options=None)

Adds the given layer to the WebMap object.

Parameter

Description

layer

Required object. You can add:

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.

Returns

True if layer was successfully added. Else, raises an appropriate exception.

# 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
add_table(table, options=None)

Adds the given Table to the WebMap.

Parameter

Description

table

Required object. You can add:

options

Optional dict. Specify properties such as title, symbol, opacity, visibility, and renderer for the table that is added. If not specified, appropriate defaults are applied.

Returns

True if table was successfully added. Else, raises appropriate exception.

wm = WebMap()
table = Table('https://some-url.com/')
wm.add_table(table)
property basemap

Get/Set the base map layers in the WebMap.

Parameter

Description

value

Required string. What basemap you would like to apply to the map (‘topo’, ‘national-geographic’, etc.). See basemaps and gallery_basemaps for a full list.

Returns

List of basemap 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-vector', 'gray-vector', 'hybrid', 'oceans', 'osm', 'satellite', 'streets-navigation-vector', 'streets-night-vector', 'streets-relief-vector', 'streets-vector', 'terrain', '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

Note

If you set a basemap that does not have the same spatial reference as the map, the map’s spatial reference will be updated to reflect this. However, any operational layers will not be re-projected.

property basemap_switcher

Get/Set whether the basemap of the WebMap can be switched.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if Basemap switcher is enabled, False otherwise.

basemap_title(title)

Get/Set the BaseMap Title. Required string title for the basemap that can be used in a table of contents. If None is specified, the current title is returned.

property basemaps

Gets a list of possible base maps to set as the basemap for the WebMap.

property bookmarks

Get/Set whether bookmarks are enabled for the viewer widget.

Parameter

Description

value

Required list of dictionaries. The new bookmarks to be used. This will replace current bookmarks with the ones passed into the list.

Returns

Bookmarks in the WebMap item.

# Usage Example:

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)

# get current bookmarks
my_bookmarks = wm.bookmarks

# create new bookmarks to replace others
bookmark1 = {'extent': {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
            'xmin': -8425179.029160742,
            'ymin': 4189089.021381017,
            'xmax': -8409834.295732513,
            'ymax': 4203784.040068822},
            'name': 'Updated Bookmark 1',
            'thumbnail': {'url': <url for thumbnail>},
            'viewpoint': {'rotation': 30,
            'scale': 7222.3819286,
            'targetGeometry': {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
            'xmin': -8425179.029160742,
            'ymin': 4189089.021381017,
            'xmax': -8409834.295732513,
            'ymax': 4203784.040068822}}}
bookmark2 = {'extent': {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
            'xmin': -83200.034567,
            'ymin': 3127089.021381017,
            'xmax': -813434.295732513,
            'ymax': 4203784.040068822},
            'name': 'Updated Bookmark 2',
            'thumbnail': {'url': <url for thumbnail>},
            'viewpoint': {'rotation': 30,
            'scale': 7222.3819286,
            'targetGeometry': {'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
            'xmin': -8425179.029160742,
            'ymin': 4189089.021381017,
            'xmax': -8409834.295732513,
            'ymax': 4203784.040068822}}}

# set new bookmark
wm.bookmarks = [bookmark1, bookmark2]
configure_pop_ups(layer_title, field_names, visibility)

This method can be used to change the visibility of a field for a layer on the Web Map.

Note

Changes will not be seen on the Web Map viewer until the Web Map is saved or updated using the save or update method. Once this is done, reload the Web Map to see changes or view on the Portal Web Map Viewer.

Parameter

Description

layer_title

Required string. The name of the layer.

field_names

Required list of strings. The name of the field to change the visibility of.

visibility

Required bool. True if the field should be visible on the pop up for the layer, else False.

property events

Gets the events associated or attached to the widget.

Returns

A list of events attached to the widget.

property forms

The forms property retrieves the smart forms corresponding to each layer and table in the web map.

Returns

FormCollection

# 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

Gets a list of web map titles contained within the Group configured as the organization’s Basemap gallery.

get_layer(item_id=None, title=None, layer_id=None)

The get_layer method retrieves the first layer with a matching itemId, title, or layer_id in the``WebMap`` object’s operational layers.

Note

Pass one of the three parameters into the method to return the layer.

Parameter

Description

item_id

Optional string. Pass the item_id for the operational layer you are trying to reference in the WebMap. Note: Not recommended if using multiple layers from the same original item.

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

A FeatureLayer as a dictionary

get_table(item_id=None, title=None, layer_id=None)

The get_table method retrieves the first table with a matching itemId, title, or layer_id in the WebMap object’s tables.

Note

Pass one of the three parameters into the method to return the table.

Parameter

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

A Table object as a dictionary

property height

Get/Set the height of the widget.

Parameter

Description

value

Required float between 0 and 1. (e.g. 0.75)

Returns

A float representing the height of the widget

property layer_visibility

Get/Set whether layer visibility is enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if layer visibility is enabled for viewer widget, False otherwise.

property layers

Gets the operational layers in the Web Map object.

Returns

List of FeatureLayer 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

Get/Set whether legend visibility is enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if legend visibility is enabled for viewer widget, False otherwise.

move_from_basemap(layer)

Move a layer from the basemap layers to the operational layers. The reverse process of move_to_basemap.

Parameter

Definition

layer

Required Dictionary. The layer dictionary that will be sent to operational layers. This dictionary is found when calling the definition property on the WebMap. The layer must already be a part of the baseMapLayers.

Returns

The WebMap definition if successful, else an error.

wm = WebMap(<webmap_item_id>)
layer = wm.definition["baseMap"]["baseMapLayer"][0]
wm.move_from_basemap(layer)
wm.update()
move_to_basemap(layer)

Move a layer to be a basemap layer. A basemap layer is a layer that provides geographic context to the map. A web map always contains a basemap. The following is a list of possible basemap layer types:

  • Image Service Layer

  • Image Service Vector Layer

  • Map Service Layer

  • Tiled Image Service Layer

  • Tiled Map Service Layer

  • Vector Tile Layer

Parameter

Definition

layer

Required Dictionary. The layer dictionary that will be sent to basemap layers. This dictionary is found when calling the layers property on the WebMap. The layer must already be in the WebMap.

Returns

The WebMap definition if successful, else an error.

# Create a WebMap from an existing WebMap Item.
wm = WebMap(<webmap_item_id>)
# Get and add the layer to the map
vtl = gis.content.get("<vector tile layer id>")
wm.add_layer(vtl.layers[0])
# Move the layer to the basemap
layer = wm.layers[0]
wm.move_to_basemap(layer)
wm.update()
property navigation

Get/Set whether navigation is enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if navigation is enabled for viewer widget, False otherwise.

property offline_areas

The offline_areas property is the resource manager for offline areas cached for the WebMap object.

Note

To create, edit, and manage offline map areas for a web map, you must be the owner of the map and have privileges to create content.

Note

You cannot share a web map that contains an offline map area with a group that allows members to update all items, and organization administrators cannot change ownership of a web map that contains an offline map area.

Returns

The OfflineMapAreaManager for the WebMap object.

property pop_ups

Get/Set whether pop ups are enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if popups are enabled for viewer widget, False otherwise.

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)

The print method prints the WebMap object to a printable file such as a PDF, PNG32, JPG.

Note

The render and print operations happen server side (ArcGIS Online or Enterprise) and not on the client.

The print method takes the state of the WebMap, renders and returns either a page layout or a map without page surrounds of the specified extent in raster or vector format.

Parameter

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

Optional tuple. Specify the dimensions of the output file in pixels. If the layout_template is not MAP_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 parameter

  • read 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 run get_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 by endTime) 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 include title, copyright text, scale bar, author name, and custom text elements. For more details, see ExportWebMap specification.

Returns

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

The remove_layer method removes the specified layer from the WebMap.

Note

A user can get the list of layers in map using the layers property and pass one of those layers to this method for removal from the map.

Parameter

Description

layer

Required object. Pass the FeatureLayer 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)

The remove_table method removes the specified table from the WebMap.

Note

A user can get the list of tables in map using the tables property and pass one of those tables to this method for removal from the map.

Parameter

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 layers property.

save(item_properties, thumbnail=None, metadata=None, owner=None, folder=None)

Saves the WebMap object as 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 web map Item in your GIS.

Note

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 WebMap item with your changes, call the update method instead.

Parameter

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 subtypes, 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 the Common Parameters page in the ArcGIS REST API documentation.

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

Get/Set the scale bar type for the viewer widget.

Parameter

Description

value

Required string. Values: ‘none’ (disable) | ‘line’ | ‘ruler’

Returns

A string representing the scale bar type. If “none” then it is disabled.

property search

Get/Set whether search is enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if search is enabled for viewer widget, False otherwise.

property tables

Gets the tables in the WebMap object.

Returns

List of Table 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)

The update method 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.

Parameter

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 the common parameters page in the ArcGIS REST API documentation.

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...'
update_drawing_info(layer, label_info=None, renderer=None, transparency=None, show_labels=None)

Method to alter a WebMap layer’s drawing info. Works for standalone layers and individual layers found within group layers. Allows for a user to manually add their own renderers and label classes, toggle whether the labels are visible, and control the transparency of a layer. Useful in tandem with the map widget, allowing for style changes without opening the online map viewer.

Note

In order to save changes made through this method, call WebMap.update() or WebMap.save().

Parameter

Description

layer

Required FeatureLayer or Feature Layer dictionary. The existing WebMap layer to be changed.

Note

In order for this method to work, the layer must be set to have its properties stored in the web map, not the source layer. This is the default setting, and can be confirmed or changed in the online Map Viewer. (Layer properties -> information)

label_info

Optional list of dictionaries. Each dictionary in the list corresponds to a label class. Determines labeling conventions of the passed layer.

renderer

Optional dictonary. Can be manually constructed or the output of generate_renderer(). Determines the layer style of the passed layer.

transparency

Optional int. Determines transparency/opacity of the layer on 0-100 scale, with 0 being fully opaque and 100 being fully transparent.

show_labels

Optional boolean. Determines whether the layer labels are visible or not.

Hint:

Accessing the layers of your Webmap allows you to view the current renderer and label info dictionaries, allowing you to easily copy them and amend the desired details.

Example

# Create Webmap from webmap item, choose a layer to edit
wm = WebMap(<wm_item_id>)
change_layer = wm.layers[0]

# Specify renderer dictionary and labeling info dictionary/dictionaries
rend = {
    "type": "simple",
    "symbol": {
        "type": "esriSLS",
        "color": [200, 50, 0, 250],
        "width": 1,
        "style": "esriSLSSolid"
    }
}

label = [
    {
        "labelExpression": "[llid]",
        "labelExpressionInfo": {"expression": "$feature["llid"]"},
        "labelPlacement": "esriServerLinePlacementCenterAlong",
        "maxScale": 0,
        "minScale": 2311163,
        "repeatLabel": True,
        "symbol": {
            "type": "esriTS",
            "color": [0, 105, 0, 255],
            "font": {"family": "Arial", "size": 9.75},
            "horizontalAlignment": "center",
            "kerning": True,
            "haloColor": [211, 211, 211, 250],
            "haloSize": 1,
            "rotated": False,
            "text": "",
            "verticalAlignment": "baseline",
            "xoffset": 0,
            "yoffset": 0,
            "angle": 0
        }
    }
]

# Call the function. This automatically updates the Webmap info
wm.update_drawing_info(
    change_layer,
    label_info = label,
    renderer = rend,
    transparency = 40,
    show_labels = True,
)
update_layer(layer)

To update the layer dictionary for a layer in the map. For example, to update the renderer dictionary for a layer and have it by dynamically changed on the webmap. Can be used to configure the pop_ups dictionary, renderer, or any other part of the Feature Layer properties.

Parameter

Description

layer

Required FeatureLayer or Feature Layer dictionary. The existing webmap layer with updated properties. In order to get a layer on the webmap, use the layers method and assign the output to a value. Make edits on this value and pass it in as a dict to update the rendering on the map.

Warning

If the itemId of the feature layer is changed, this will not work.

# Create Webmap from webmap item
wm = WebMap(<wm_item_id>)

# Get a layer and edit the color
fl = wm.layers[0]
fl["layerDefinition"]["drawingInfo"]["renderer"]["symbol"]["color"] = [0, 0, 0, 255]

# Update the layer to see it render on map
wm.update_layer(dict(my_lyr))

# Save with the updates
wm_properties= {"title": "Test Update", "tags":["update_layer"], "snippet":"Updated a layer and now save"}
wm.save(wm_properties)
property view_bookmarks

Get/Set whether bookmarks are enabled for the dashboard widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if bookmarks are enabled for viewer widget, False otherwise.

property width

Get/Set the width of the viewer widget.

Parameter

Description

value

Required float between 0 and 1. (e.g. 0.75)

Returns

A float representing the width of the widget

property zoom

Get/Set whether zoom is enabled for the viewer widget.

Parameter

Description

value

Required bool. True to enable, False to disable

Returns

True if zoom is enabled for viewer widget, False otherwise.

OfflineMapAreaManager

class arcgis.mapping.OfflineMapAreaManager(item, gis)

Bases: object

The OfflineMapAreaManager is a helper class to manage offline map areas for a Web Map Item. Objects of this class should not be initialized directly, but rather accessed using the offline_areas property on a WebMap object.

>>> from arcgis.gis import GIS
>>> from arcgis.mapping import WebMap

>>> gis = GIS(profile="your_Web_GIS_profile")

>>> wm_item = gis.content.get("<web map id>")
>>> wm_obj = WebMap(wm_item)

>>> oma_mgr = wm_obj.offline_areas
<arcgis.mapping._types.OfflineMapAreaManager at <memory_addr>>

Note

There are important concepts to understand about offline mapping before the properties and methods of this class will function properly. Both reference basemaps and operational layers contained in a Web Map must be configured very specifically before they can be taken offline. See the documentation below for full details:

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)

This method creates offline map area items and packages for ArcGIS Runtime powered applications to use. The method creates two different types of Items

  • Map Area items for the specified extent, bookmark, or polygon

  • Map Area Packages corresponding to the operational layer(s) and basemap layer(s) within the extent, bookmark or polygon area

Note

Packaging will fail if the size of the offline map area, when packaged, is larger than 2.5 GB.

  • If packaging fails, try using a smaller bookmark, extent or geometry for the area argument.

  • If the map contains feature layers that have attachments, you can exclude attachments from the offline package to decrease the package size.

  • If the map includes tile layers, use the tile_services argument to constrain the number of levels included in the resulting packages. This is typically required to reduce the tile package size for the basemap layer(s) in ArcGIS Enterprise.

Note

Only the owner of the Web Map item can create offline map areas.

Parameter

Description

area

Required bookmark, extent, or Polygon object. Specify as either:

  • bookmark name

    >>> wm_item = gis.content.get("<web map id>")
    >>> wm_obj = WebMap(wm_item)
    
    >>> wm_bookmarks = wm_obj.bookmarks
    >>> area = wm_bookmarks[0]
    
  • extent: as a list of coordinate pairs:

    >>> area = [['xmin', 'ymin'], ['xmax', 'ymax']]
    
  • extent: as a dictionary:

    >>> area = {
                'xmin': <value>,
                'ymin': <value>,
                'xmax': <value>,
                'ymax': <value>,
                'spatialReference' : {'wkid' : <value>}
               }
    
  • polygon: as a Polygon object

Note

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.

Note

These items will not display when viewing the content folder in a web browser. They will display in the Portal tab of the Content Pane in ArcGIS Pro.

min_scale

Optional integer. Specify the minimum scale to cache tile and vector tile layers. When zoomed out beyond this scale, cached layers would not display.

Note

The min_scale value is always larger than the max_scale.

max_scale

Optional integer. 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. Thw refresh will occur on the ‘n’ day of the month.

  • day_of_week - a value between 0-6 where 0 is Sunday and 6 is Saturday.

# Example **Daily**: every day at 10:30 AM UTC

 >>> refresh_rates = {
                      "hour": 10,
                      "minute" : 30
                     }

# Example **Weekly**: every Wednesday at 11:59 PM UTC

 >>> refresh_rates = {
                      "hour" : 23,
                      "minute" : 59,
                      "day_of_week" : 4
                     }

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.

>>> ignore_layers = [
                     "https://services.arcgis.com/ERmEceOGq5cHrItq/arcgis/rest/services/SaveTheBaySync/FeatureServer/1",
                     "https://services.arcgis.com/ERmEceOGq5cHrItq/arcgis/rest/services/WildfireSync/FeatureServer/0"
                    ]

tile_services

Optional List. An list of Python dictionary objects that contains information about the export tiles-enabled 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.

>>> tile_services = [
                     {
                      "url": "https://tiledbasemaps.arcgis.com/arcgis/rest/services/World_Imagery/MapServer",
                      "levels": "17,18,19"
                     }

Note

This argument should be specified when using ArcGIS Enterprise items. The number of levels included greatly impacts the overall size of the resulting packages to keep them under the 2.5 GB limit.

future

Optional boolean. If True, a future object will be returned and the process will return control to the user before the task completes. If False, control returns once the operation completes. The default is False.

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 of comma-separated values, or a list of strings for each tag.

snippet

Optional string. Provide a short summary (limit to max 250 characters) of the what the item is.

Returns

Map Area Item, or if future=True, a PackagingJob object to further query for results.

# USAGE EXAMPLE #1: Creating offline map areas using *scale* argument

>>> from arcgis.gis import GIS
>>> from arcgis.mapping import WebMap

>>> gis = GIS(profile="your_online_organization_profile")

>>> wm_item = gis.content.get("<web_map_id>")
>>> wm_obj = WebMap(wm_item)

>>> 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_item.layers[-1]

>>> north_bed = wm_obj.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])

# USAGE Example #2: ArcGIS Enterprise web map specifying *tile_services*

>>> gis = GIS(profile="your_enterprise_profile")

>>> wm_item = gis.content.get("<item_id>")
>>> wm_obj = WebMap(wm_item)

# Enterprise: Get the url for tile services from basemap
>>> basemap_lyrs = wm_obj.definition["baseMap"]["baseMapLayers"]
>>> basemap_lyrs

    [
     {'id': '18d9e5e151c-layer-2',
      'title': 'Light_Gray_Export_AGOL_Group',
      'itemId': '042f5e5aadcb8dbd910ae310b1f26d18',
      'layerType': 'VectorTileLayer',
      'styleUrl': 'https:/example.com/portal/sharing/servers/042f5e5aadcb8dbd910ae310b1f26d1/rest/services/World_Basemap_Export_v2/VectorTileServer/resources/styles/root.json'}
    ]

# Get the specific Tile Layer item to see options for levels
>>> vtl_item = gis.content.get(basemap_lyrs[0]["itemId"])
>>> vtl_lyr = vtl_item.layers[0]
>>> print(f"min levels: {vtl_lyr.properties['minLOD']}")
>>> print(f"max levels: {vtl_lyr.properties['maxLOD']}")

    min levels: 0
    max levels: 16

>>> vtl_svc_url = vtl_item.layers[0].url
>>> vtl_svc_url
https:/example.com/portal/sharing/servers/042f5e5aadcb8dbd910ae310b1f26d1/rest/services/World_Basemap_Export_v2/VectorTileServer

# Get a list of bookmark names to iterate through
>>> bookmarks = wm_obj.bookmarks
>>> bkmrk_names = [bookmark["name"] for bookmark in bookmarks]
>>> bname = bkmrk_names[1]

>>> oma = offline_mgr.create(area=bname,
                             item_properties={"title": bname + "_OMA",
                                              "tags": "offline_mapping,administrative boundaries,parks",
                                              "snippet": bname + " in County",
                                              "description": "Offline mapping area in " + bname + " for sync"},
                             tile_services=[{"url": vtl_svc_url,
                                             "levels": "6,7,8,9,10,11,12,13"}])
>>> oma
<Item title:"County_OMA" type:Map Area owner:gis_user>

>>> # List packages created:
>>> for oma_pkg in oma.related_items("Area2Package", "forward"):
>>>     print(f"{oma_pkg.title:60}{oma_pkg.type}")

<County_Layer-<id_string>                SQLite Geodatabase
<VectorTileServe-<id_string>             Vector Tile Package

Note

This method executes silently. To view informative status messages, set the verbosity environment variable as shown below prior to running the method:

# USAGE EXAMPLE: setting verbosity

>>> from arcgis import env
>>> env.verbose = True
list()

Retrieves a list of all Map Area items for the WebMap object.

Note

Map Area items and the corresponding offline packages share a relationship of type Area2Package. You can use this relationship to get the list of package items cached for each map area item. Refer to the Python snippet below for the steps:

# USAGE EXAMPLE: Listing Map Area Items

>>> from arcgis.gis import GIS
>>> from arcgis.mapping import WebMap

>>> wm_item = gis.content.search("*", "Web Map")[0]
>>> wm_obj = WebMap(wm_item)

>>> all_map_areas = wm.offline_areas.list()
>>> all_map_areas

[<Item title:"Ballerup_OMA", type:Map Area owner:gis_user1>,
 <Item title:"Viborg_OMA", type:Map Area owner:gis_user1>]

# USAGE Example: Inspecting Map Area packages

>>> area1 = all_map_areas[0]
>>> area1_packages = area1.related_items("Area2Package","forward")

>>> for pkg in area1_packages:
>>>     print(f"{pkg.title}")
<<<     print(f"{' ' * 2}{pkg.type}")
>>>     print(f"{' ' * 2}{pkg.homepage}")

VectorTileServe-<value_string>
  Vector Tile Package
  https://<organziation_url>/home/item.html?id=<item_id>


DK_lau_data-<value_string>
  SQLite Geodatabase
  https://organization_url/home/item.html?id=<item_id>
Returns

A List of Map Area :class`items <arcgis.gis.Item>` related to the Web Map item.

modify_refresh_schedule(item, refresh_schedule=None, refresh_rates=None)

The modify_refresh_schedule method modifies an existing offline package’s refresh schedule.

Parameter

Description

item

Required Item object. 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

A boolean indicating success (True), or failure (False)

## 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 defining how available offline editing, basemap, and read-only layers behave in the web map application. For further reading about concepts for working with web maps offline, see Configure the map to work offline. Also, see the applicationProperties object in the Web Map specification.

Parameter

Description

values

Required Dict. The key/value pairs that define the offline application properties.

The dictionary supports the following keys:

Key

Values

download

Optional string. Possible values:

  • None

  • features

  • features_and_attachments

When editing layers, the edits are always sent to the server. This string argument indicates which data is retrieved from the server.

  • If argument is None - only the schema is written since neither features nor attachments are retrieved

  • If argument is features - a full sync without downloading attachments occurs

  • If argument is features_and_attachments, which is the Default - both features and attachments are retrieved

sync

sync applies to editing layers only. This string value indicates how the data is synced:

  • sync_features_and_attachments - bidirectional sync

  • sync_features_upload_attachments - bidirectional sync for features 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

# USAGE EXAMPLE

>>> from arcgis.gis import GIS
>>> from arcgis.mapping import WebMap

>>> wm_item = gis.content.get("<web_map_id>")
>>> wm_obj = WebMap(wm_item)

>>> offline_mgr = wm_obj.offline_areas
>>> offline_mgr.offline_properties = {"download": "features",
                                      "sync": "sync_features_upload_attachments"}
update(offline_map_area_items=None, future=False)

The update method refreshes existing map area packages associated with each of the 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. See Refresh Map Area Package for more information.

Parameter

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.

Note

To get the list of Map Area items related to the WebMap object, call the list() method on the OfflineMapAreaManager for the WebMap.

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 before running the code:

USAGE EXAMPLE: setting verbosity

from arcgis import env
env.verbose = True

PackagingJob

class arcgis.mapping.PackagingJob(future, notify=False)

Bases: object

The PackagingJob class represents a Single Packaging Job.

Parameter

Description

future

Required Future object. The async object created by the geoprocessing GPTask.

notify

Optional Boolean. When set to True, a message will inform the user that the geoprocessing task has completed. The default is False.

cancel()

The cancel method attempts to cancel the job.

Note

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

A boolean indicating the call will be cancelled (True), or cannot be cancelled (False)

cancelled()

The cancelled method retrieves whether the call was successfully cancelled.

Returns

A boolean indicating success (True), or failure (False)

done()

The done method retrieves whether the call was successfully cancelled or finished running.

Returns

A boolean indicating success (True), or failure (False)

property ellapse_time

The ellapse_time property retrieves the Ellapse Time for the Job.

Returns

The elapsed time

result()

The result method retrieves the value returned by the call.

Note

If the call hasn’t yet completed then this method will wait.

Returns

An Object

running()

The running method retrieves whether the call is currently being executed and cannot be cancelled.

Returns

A boolean indicating success (True), or failure (False)

property status

Get the GP status of the call.

Returns

A String

Working with 3D Maps

WebScene

class arcgis.mapping.WebScene(websceneitem)

Bases: collections.OrderedDict

The WebScene 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]

SceneLayer

class arcgis.mapping.SceneLayer(url, gis=None)

Bases: arcgis.gis.Layer

The SceneLayer class represents a Web scene layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features.

Note

Web scene layers can be used to represent 3D points, point clouds, 3D objects and integrated mesh layers.

Parameter

Description

url

Required string, specify the url ending in /SceneServer/

gis

Optional 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'

SceneLayerManager

class arcgis.mapping.SceneLayerManager(url, gis=None, scene_lyr=None)

Bases: arcgis.gis._GISResource

The SceneLayerManager class allows administration (if access permits) of ArcGIS Online hosted scene layers. A SceneLayerManager 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.

Parameter

Description

job_id

Required String. The job id to cancel.

edit(item)

The edit method edits from an Item object.

Parameter

Description

item

Required ItemId or Item object. The TPK file’s item id. This TPK file contains to-be-extracted bundle files which are then merged into an existing cache service.

Returns

A dictionary

import_package(item)

The import method imports from an Item object.

Parameter

Description

item

Required ItemId or Item object. The TPK file’s item id. This TPK file contains to-be-extracted bundle files which are then merged into an existing cache service.

Returns

A dictionary

job_statistics(job_id)

Returns the job statistics for the given jobId

jobs()

The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.

rebuild_cache(layers)

The rebuild_cache operation update the scene layer cache to reflect any changes made to the feature layer used to publish this scene layer. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.

Parameter

Description

layers

Required int or list of int. Comma separated values indicating the id of the layers to rebuild in the cache.

Ex: [0,1,2]

refresh()

The refresh operation refreshes a service, which clears the web server cache for the service.

rerun_job(job_id, code)

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.

Parameter

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

A boolean or dictionary

swap(target_service_name)

The swap operation replaces the current service cache with an existing one.

Note

The swap operation is for ArcGIS Online only.

Parameter

Description

target_service_name

Required string. Name of service you want to swap with.

Returns

dictionary indicating success or error

update()

The update method starts update generation for ArcGIS Online. It updates the underlying source dataset for the service, essentially refreshing the underlying package data.

Returns

Dictionary.

update_attribute(layers)

Update atrribute is a “light rebuild” where attributes of the layers selected are updated and can be used for change tracking. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.

Parameter

Description

layers

Required int or list of int. Comma seperated values indicating the id of the layers to update in the cache.

Ex: [0,1,2]

update_cache(layers)

Update Cache is a “light rebuild” where attributes and geometries of the layers selected are updated and can be used for change tracking on the feature layer to only update nodes with dirty tiles. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.

Parameter

Description

layers

Required int or list of int. Comma seperated values indicating the id of the layers to update in the cache.

Ex: [0,1,2]

EnterpriseSceneLayerManager

class arcgis.mapping.EnterpriseSceneLayerManager(url, gis=None, scene_lyr=None)

Bases: arcgis.gis._GISResource

The EnterpriseSceneLayerManager class allows administration (if access permits) of ArcGIS Enterprise hosted scene layers. A SceneLayer offers access to layer content.

Note

Url must be admin url such as: https://services.myserver.com/arcgis/rest/admin/services/serviceName/SceneServer/

change_provider(provider)

Allows for the switching of the service provide and how it is hosted on the ArcGIS Server instance.

Values:

  • ‘ArcObjects’ means the service is running under the ArcMap runtime i.e. published from ArcMap

  • ‘ArcObjects11’: means the service is running under the ArcGIS Pro runtime i.e. published from ArcGIS Pro

  • ‘DMaps’: means the service is running in the shared instance pool (and thus running under the ArcGIS Pro provider runtime)

Returns

Boolean

delete()

deletes a service from arcgis server

edit(service_dictionairy)

To edit a service, you need to submit the complete JSON representation of the service, which includes the updates to the service properties. Editing a service causes the service to be restarted with updated properties.

Parameter

Description

service_dictionairy

Required dict. The service JSON as a dictionary.

Returns

boolean

rebuild_cache(layer=None, extent=None, area_of_interest=None)

The rebuild_cache operation update the scene layer cache to reflect any changes made to the feature layer used to publish this scene layer. The results of the operation is the url to the scene service once it is done rebuilding.

Parameter

Description

layer

Optional list of integers. The list of layers to cook.

extent

Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.

area_of_interest

Optional dict representing a feature. Specify the updated area of interest.

Syntax:
{

“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: False

}

Returns

If successful, the url to the scene service

start()

starts the specific service

stop()

stops the specific service

update_attribute(layer=None, extent=None, area_of_interest=None)

Update atrribute is a “light rebuild” where attributes of the layers selected are updated and can be used for change tracking. The results of the operation is the url to the scene service once it is done updating.

Parameter

Description

layer

Optional list of integers. The list of layers to cook.

extent

Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.

area_of_interest

Optional dict representing a feature. Specify the updated area of interest.

Syntax:
{

“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: false

}

Returns

If successful, the url to the scene service

update_cache(layer=None, extent=None, area_of_interest=None)

Update Cache is a “light rebuild” where attributes and geometries of the layers selected are updated and can be used for change tracking on the feature layer to only update nodes with dirty tiles,. The results of the operation is the url to the scene service once it is done updating.

Parameter

Description

layer

Optional list of integers. The list of layers to cook.

extent

Optional dict. The updated extent to be used. If nothing is specified, the default extent is used.

area_of_interest

Optional dict representing a feature. Specify the updated area of interest.

Syntax:
{

“displayFieldName”: “”, “geometryType”: “esriGeometryPolygon”, “spatialReference”: { “wkid”: 54051, “latestWkid”: 54051 }, “fields”: [ { “name”: “OID”, “type”: “esriFieldTypeOID”, “alias”: “OID” }, { “name”: “updateGeom_Length”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Length” }, { “name”: “updateGeom_Area”, “type”: “esriFieldTypeDouble”, “alias”: “updateGeom_Area” } ], “features”: [], “exceededTransferLimit”: False

}

Returns

If successful, the url to the scene service

BuildingLayer

class arcgis.mapping.BuildingLayer(url, gis=None)

Bases: arcgis.gis.Layer

The BuildingLayer class represents a Web building layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

IntegratedMeshLayer

class arcgis.mapping.IntegratedMeshLayer(url, gis=None)

Bases: arcgis.gis.Layer

The IntegratedMeshLayer class represents a Web scene Integrated Mesh layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

Tiles3DLayer

class arcgis.mapping.Tiles3DLayer(url, gis=None)

Bases: arcgis.gis.Layer

The Tiles3DLayer class represents a Web scene 3D Tile Service Layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

Description

url

Required string, specify the url ending in /3DTilesServer/

gis

Optional GIS object. If not specified, the active GIS connection is used.

property manager

The manager property returns an instance of Tiles3DLayerManager class which provides methods and properties for administering this service.

Object3DLayer

class arcgis.mapping.Object3DLayer(url, gis=None)

Bases: arcgis.gis.Layer

The Object3DLayer represents a Web scene 3D Object layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

Point3DLayer

class arcgis.mapping.Point3DLayer(url, gis=None)

Bases: arcgis.gis.Layer

The Point3DLayer class represents a Web scene 3D Point layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

PointCloudLayer

class arcgis.mapping.PointCloudLayer(url, gis=None)

Bases: arcgis.gis.Layer

The PointCloudLayer class represents a Web scene Point Cloud layer.

Note

Point Cloud layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

VoxelLayer

class arcgis.mapping.VoxelLayer(url, gis=None)

Bases: arcgis.gis.Layer

The VoxelLayer class represents a Web Scene Voxel layer.

Note

Web scene layers are cached web layers that are optimized for displaying a large amount of 2D and 3D features. See the SceneLayer class for more information.

Parameter

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.VoxelLayer

print(s_layer.properties.layers[0].name)
>> 'your layer name'
property manager

The manager property returns an instance of SceneLayerManager class or EnterpriseSceneLayerManager class which provides methods and properties for administering this service.

Working with Map Service Layers

MapServiceLayer

class arcgis.mapping.MapServiceLayer(url, gis=None, container=None, dynamic_layer=None)

Bases: arcgis.gis.Layer

The MapServiceLayer class is a factory that generates the Map Service Layers.

Parameter

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

The MapFeatureLayer class represents Map Feature Layers. 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

The attachements property provides a manager to work with attachments if the MapFeatureLayer supports this functionality.

property container

The container property represents the MapImageLayer to which this layer belongs.

export_attachments(output_folder, label_field=None)

The export_attachments method exports attachments from the map feature layer in Imagenet format using the output_label_field.

Parameter

Description

output_folder

Required String. Output folder path 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.

Returns

A path to the exported attachments

classmethod fromitem(item, layer_id=0)

The fromitem method creates a MapFeatureLayer from a GIS Item.

Parameter

Description

item

Required Item object. The type of item should be a MapServiceLayer object.

layer_id

Optional integer. The id of the layer in the Map Service’s Layer. The default is 0.

Returns

A MapFeatureLayer object

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer, MapFeatureLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_feature_layer = MapFeatureLayer.fromitem(item = map_image_item,
                                                 layer_id = 2)
>>> print(f"{map_feature_layer.properties.name:30}{type(map_feature_layer)}")
<State Boundaries              <class 'arcgis.mapping._msl.layer.MapFeatureLayer'>>
generate_renderer(definition, where=None)

The generate_renderer 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.

Note

If the operation is performed on a table, the result is a renderer object containing the data classes and no symbols.

Parameter

Description

definition

Required dict. The definition using the renderer that is generated. Use either class breaks or unique value classification definitions. See the classification definitions page in the ArcGIS REST API documentation for more information.

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 get_html_popup resource provides details about the HTML pop-up authored by the user using ArcGIS Pro or ArcGIS Desktop.

Parameter

Description

oid

Optional string. Object id of the feature to get the HTML popup.

Returns

A string

get_unique_values(attribute, query_string='1=1')

The get_unique_values method retrieves a list of unique values for a given attribute.

Parameter

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.

Returns

A List

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer, MapFeatureLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_feature_layer = MapFeatureLayer.fromitem(item = map_image_item,
                                                 layer_id = 2)
>>> unique_values = map_feature_layer.get_unique_values(attribute ="Name",
                                        query_string ="name_2 like '%K%'")
>>> type(unique_values)
<List>
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)

The query method queries a map feature layer based on a sql statement.

Parameter

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.

Value options:

esriSRUnit_Meter | esriSRUnit_StatuteMile | esriSRUnit_Foot | esriSRUnit_Kilometer | esriSRUnit_NauticalMile | esriSRUnit_USNauticalMile

time_filter

Optional list of startTime and endTime values. :Syntax:

>>> time_filter=[<startTime>, <endTime>]

Note

Specified as datetime.date, datetime.datetime or timestamp in milliseconds

geometry_filter

Optional filter object. Allows for the information to be filtered on spatial relationship with another geometry.

max_allowable_offset

Optional float. This option can be used to specify the max_allowable_offset to be used for generalizing geometries returned by the query operation in the units of out_sr. If out_sr is not specified, the value is in units of the spatial reference of the layer.

out_sr

Optional Integer. The WKID for the spatial reference of the returned geometry.

geometry_precision

Optional Integer. This option can be used to specify the number of decimal places in the response geometries returned by the query operation. This applies to X and Y values only (not m or z-values).

gdb_version

Optional string. The geodatabase version to query. This parameter applies only if the isDataVersioned property of the layer is true. If not specified, the query will apply to the published map’s version.

return_geometry

Optional boolean. If true, geometry is returned with the query. Default is true.

return_distinct_values

Optional boolean. If True, it returns distinct values based on fields specified in out_fields. This parameter applies only if the supportsAdvancedQueries property of the layer is true.

return_ids_only

Optional boolean. Default is False. If True, the response only includes an array of object IDs. Otherwise, the response is a FeatureSet.

return_count_only

Optional boolean. If True, the response only includes the count of features/records satisfying the query. Otherwise, the response is a FeatureSet. The default is False. This option supersedes the returns_ids_only 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 satisying 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 by which to order the results. Use ASC or DESC for ascending or descending, respectively, following every field to be ordered:

>>> order_by_fields = "STATE_NAME ASC, RACE DESC, GENDER ASC"

group_by_fields_for_statistics

Optional string. One or more field names on which to group results for calculating the statistics.

>>> group_by_fields_for_statiscits = "STATE_NAME, GENDER"

out_statistics

Optional List. The definitions for one or more field-based statistics to be calculated.

Syntax

>>> out_statistics = [
                        {
                          "statisticType": "<count | sum | min | max | avg | stddev | var>",
                          "onStatisticField": "Field1",
                          "outStatisticFieldName": "Out_Field_Name1"
                        },
                        {
                          "statisticType": "<count | sum | min | max | avg | stddev | var>",
                          "onStatisticField": "Field2",
                          "outStatisticFieldName": "Out_Field_Name2"
                        }
                     ]

return_z

Optional boolean. If True, Z values are included in the results if the features have Z values. Otherwise, Z values are not returned. The default is False.

return_m

Optional boolean. If True, M values are included in the results if the features have M values. Otherwise, M values are not returned. The default is False.

multipatch_option

Optional x/y footprint. This option dictates how the geometry of a multipatch feature will be returned.

result_offset

Optional integer. This option can be used for fetching query results by skipping the specified number of records and starting from the next record (that is, resultOffset + ith value). This option is ignored if return_all_records is True (i.e. by default).

result_record_count

Optional integer. This option can be used for fetching query results up to the result_record_count specified. When result_offset is specified but this parameter is not, the map service defaults it to max_record_count. The maximum value for this parameter is the value of the layer’s maxRecordCount property. This option is ignored if return_all_records is True (i.e. by default).

quantization_parameters

Optional dict. Used to project the geometry onto a virtual grid, likely representing pixels on the screen.

return_centroid

Optional boolean. Used to return the geometry centroid associated with each feature returned. If True, the result includes the geometry centroid. The default is False.

return_all_records

Optional boolean. When True, the query operation will call the service until all records that satisfy the where_clause are returned.

Note

result_offset and result_record_count will be ignored if set to True. If return_count_only, return_ids_only, or return_extent_only are True, this parameter is ignored.

result_type

Optional string. Controls the number of features returned by the operation. Options: None | standard | tile

Note

See Query (Feature Service/Layer) for full explanation.

historic_moment

Optional integer. The historic moment to query. This parameter applies only if the layer is archiving enabled and the supportsQueryWithHistoricMoment property is set to true. This property is provided in the layer’s properties resource. If not specified, the query will apply to the current features.

sql_format

Optional string. The sql_format parameter can be either standard SQL92 or it can use the native SQL of the underlying datastore. The default is None, which means it depends on the useStandardizedQuery layer property. Values: None | standard | 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 the exceededTransferLimit: True property.

When set to False and querying with resultType = tile, features are not returned when the results include exceededTransferLimit: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.

as_df

Optional boolean. If True, the results are returned as a DataFrame instead of a FeatureSet.

datum_transformation

Optional Integer/Dictionary. This parameter applies a datum transformation while projecting geometries in the results when out_sr is different than the layer’s spatial reference. When specifying transformations, you need to think about which datum transformation best projects the layer (not the feature service) to the outSR and sourceSpatialReference property in the layer properties. For a list of valid datum transformation ID values ad well-known text strings, see Coordinate systems and transformations. For more information on datum transformations, please see the transformation parameter in the Project operation.

Example:

Inputs

Description

WKID

Integer.

>>> datum_transformation=4326

WKT

Dict.

>>> datum_transformation = {"wkt": "<WKT>"}

Composite

Dict.

>>> datum_transformation = {"geoTransforms" : [
                                               {"wkid" : "<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.

>>> range_values = [
                    {
                     "name": "range name" ,
                     # single value or a value-range
                     "value": <value> or [ <value1>, <value2> ]

                    },
                    {
                     "name": "range name 2",
                     "value": <value> or  [ <value3>, <value4> ]
                    }
                   ]

Note

None is allowed in value-range case to indicate infinity

# all features with values <= 1500
>>> range_values = [
                    {"name" : "range name",
                     "value" : [None, 1500]}
                   ]

# all features with values >= 1000
>>> range_values = [
                    {"name" : "range name",
                     "value" : [1000, None]}
                   ]

parameter_values

Optional Dict. Allows you to filter the layers by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.

When a parameterInfo allows multiple values, you must pass them in an array.

Note

Check parameterValues at the Query (Map Service/Layer) for details on parameterized filters.

kwargs

Optional 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 at Query (Feature Service/Layer).

Returns

A FeatureSet containing the features matching the query unless another

return type is specified, such as count.

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer, MapFeatureLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_feature_layer = MapFeatureLayer.fromitem(item = map_image_item,
                                                 layer_id = 2)
>>> query_count = map_feature_layer.query(where "1=1",
                            text = "Hurricane Data",
                            units = "esriSRUnit_Meter",
                            return_count_only = True,
                            out_statistics = [
                                                {
                                                "statisticType": "count",
                                                "onStatisticField": "Field1",
                                                "outStatisticFieldName": "Out_Field_Name1"
                                                },
                                                {
                                                "statisticType": "avg",
                                                "onStatisticField": "Field2",
                                                "outStatisticFieldName": "Out_Field_Name2"
                                                }
                                            ],
                            range_values= [
                                    {
                                      "name": "range name",
                                      "value": [None, 1500]
                                      },
                                      {
                                        "name": "range name 2",
                                        "value":[1000, None]
                                      }
                                    }
                                ]
                            )
>>> query_count
<149>

The query_related_records operation is performed on a MapFeatureLayer resource. The result of this operation are FeatureSet objects grouped by source layer/table object IDs. Each FeatureSet contains Feature objects including the values for the fields requested by the user.

Note

For related layers, if you request geometry information, the geometry of each feature is also returned in the feature set. For related tables, the feature set does not include geometries.

Note

See the query method for more information.

Parameter

Description

object_ids

Required string. The object IDs of the table/layer to be queried

relationship_id

Required string. The ID of the relationship to be queried.

out_fields

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.

Note

The renderer property overrides the default symbology when displaying it on a WebMap.

Returns

InsensitiveDict: A case-insensitive dict like object used to update and alter JSON A varients of a case-less dictionary that allows for dot and bracket notation.

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 set using the time_filter property. Time can be filtered as Python datetime, objects or strings representing Unix epoch values in milliseconds. An extent can be specified by separating the start and stop values comma.

>>> import datetime as dt

>>> map_feature_lyr.time_filter = [dt.datetime(2021, 1, 1), dt.datetime(2022, 1, 10)]

MapRasterLayer

class arcgis.mapping.MapRasterLayer(url, gis=None, container=None, dynamic_layer=None)

Bases: arcgis.mapping._msl.layer.MapFeatureLayer

The MapRasterLayer class represents a geo-referenced image hosted in a Map Service.

MapImageLayer

class arcgis.mapping.MapImageLayer(url, gis=None)

Bases: arcgis.gis.Layer

The 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.

Note

MapImageLayer does not display tiled images. To display tiled map service layers, see TileLayer.

create_dynamic_layer(layer)

The create_dynamic_layer method creates a dynamic layer. A dynamic layer / table represents a single layer / table of a map service published by ArcGIS Server or of a registered workspace. This resource is supported only when the map image layer supports dynamic layers, as indicated by supportsDynamicLayers on the map image layer properties.

Parameter

Description

layer

Required dict. Dynamic layer/table source definition.

Syntax:

{
“id”: <layerOrTableId>,
“source”: <layer source>, //required
“definitionExpression”: “<definitionExpression>”,
“drawingInfo”:
{
“renderer”: <renderer>,
“transparency”: <transparency>,
“scaleSymbols”: <true,false>,
“showLabels”: <true,false>,
“labelingInfo”: <labeling info>
},
“layerTimeOptions”: //supported only for time enabled map layers
{
“useTime” : <true,false>,
“timeDataCumulative” : <true,false>,
“timeOffset” : <timeOffset>,
“timeOffsetUnits” : “<esriTimeUnitsCenturies,esriTimeUnitsDays,
esriTimeUnitsDecades,esriTimeUnitsHours,
esriTimeUnitsMilliseconds,esriTimeUnitsMinutes,
esriTimeUnitsMonths,esriTimeUnitsSeconds,
esriTimeUnitsWeeks,esriTimeUnitsYears |
esriTimeUnitsUnknown>”
}
}
Returns

FeatureLayer or None (if not enabled)

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> layer_to_add ={
                    "id": <layerId>,
                    "source": <layer source>
                    "definitionExpression": "<definitionExpression>",
                    "drawingInfo":
                    {
                      "renderer": <renderer>,
                      "transparency": <transparency>,
                      "scaleSymbols": <true>,
                      "showLabels": <true>,
                      "labelingInfo": <labeling info>
                    },
                    "layerTimeOptions":
                    {
                      "useTime" : <true,false>,
                      "timeDataCumulative" : <true>,
                      "timeOffset" : <timeOffset>,
                      "timeOffsetUnits" : "<esriTimeUnitsCenturies>"
                    }
                  }
>>> new_layer = map_image_item.create_dynamic_layer(layer= layer_to_add)
>>>type(new_layer)
<arcgis.features.FeatureLayer>
estimate_export_tiles_size(export_by, levels, tile_package=False, export_extent='DEFAULT', 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 exceed the maxExportTileCount limit set by the administrator of the service. The result of this operation is MapServiceJob. 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.

Parameter

Description

export_by

Required string. The criteria that will be used to select the tile service levels to export. The values can be Level IDs, cache scales or the Resolution (in the case of image services). Values:

“levelId” | “resolution” | “scale”

levels

Required string. Specify the tiled service levels for which you want to get the estimates. The values should correspond to Level IDs, cache scales or the Resolution as specified in export_by parameter. The values can be comma separated values or a range.

Example 1: 1,2,3,4,5,6,7,8,9 Example 2: 1-4,7-9

tile_package

Optional boolean. Allows estimating the size for either a tile package or a cache raster data set. Specify the value true for tile packages format and false for Cache Raster data set. The default value is False

export_extent

The extent (bounding box) of the tile package or the cache dataset to be exported. If extent does not include a spatial reference, the extent values are assumed to be in the spatial reference of the map. The default value is full extent of the tiled map service. Syntax: <xmin>, <ymin>, <xmax>, <ymax> Example: -104,35.6,-94.32,41

area_of_interest

Optional dictionary or Polygon. This allows exporting tiles within the specified polygon areas. This parameter supersedes extent parameter.

Example:

{ “features”: [{“geometry”:{“rings”:[[[-100,35],
[-100,45],[-90,45],[-90,35],[-100,35]]],
“spatialReference”:{“wkid”:4326}}}]}

asynchronous

Optional boolean. The estimate function is run asynchronously requiring the tool status to be checked manually to force it to run synchronously the tool will check the status until the estimation completes. The default is True, which means the status of the job and results need to be checked manually. If the value is set to False, the function will wait until the task completes.

Returns

dictionary

export_map(bbox, 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_map 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.

Parameter

Description

bbox

Required string. The extent (bounding box) of the exported image. Unless the bbox_sr parameter has been specified, the bbox is assumed to be in the spatial reference of the map.

bbox_sr

Optional integer, SpatialReference. The spatial reference of the bbox.

size

Optional string. size - size of image in pixels

dpi

Optional integer. dots per inch

image_sr

Optional integer, SpatialReference. The spatial reference of the output image.

image_format

Optional string. The format of the exported image. The default format is .png. Values:

png | png8 | png24 | jpg | pdf | bmp | gif | svg | svgz | emf | ps | png32

layer_defs

Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.

layers

Optional string. Determines which layers appear on the exported map. There are four ways to specify which layers are shown:

show: Only the layers specified in this list will be exported.

hide: All layers except those specified in this list will be exported.

include: In addition to the layers exported by default, the layers specified in this list will be exported.

exclude: The layers exported by default excluding those specified in this list will be exported.

transparent

Optional boolean. If true, the image will be exported with the background color of the map set as its transparent color. The default is false.

Note

Only the .png and .gif formats support transparency.

time_value

Optional list. The time instant or the time extent of the features to be identified.

time_options

Optional dict. The time options per layer. Users can indicate whether or not the layer should use the time extent specified by the time parameter or not, whether to draw the layer features cumulatively or not and the time offsets for the layer.

dynamic_layers

Optional dict. Use dynamicLayers property to reorder layers and change the layer data source. dynamicLayers can also be used to add new layer that was not defined in the map used to create the map service. The new layer should have its source pointing to one of the registered workspaces that was defined at the time the map service was created. The order of dynamicLayers array defines the layer drawing order. The first element of the dynamicLayers is stacked on top of all other layers. When defining a dynamic layer, source is required.

gdb_version

Optional string. Switch map layers to point to an alternate geodatabase version.

scale

Optional float. Use this parameter to export a map image at a specific map scale, with the map centered around the center of the specified bounding box (bbox)

rotation

Optional float. Use this parameter to export a map image rotated at a specific angle, with the map centered around the center of the specified bounding box (bbox). It could be positive or negative number.

transformations

Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different than the map service’s spatial reference. It is an array of transformation elements.

map_range_values

Optional list. Allows you to filter features in the exported map from all layer that are within the specified range instant or extent.

layer_range_values

Optional dictionary. Allows you to filter features for each individual layer that are within the specified range instant or extent. Note: Check range infos at the layer resources for the available ranges.

layer_parameter

Optional list. Allows you to filter the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.

Returns

A string, image of the map.

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_image_item.export_map(bbox="-104,35.6,-94.32,41",
                              bbox_sr = 4326,
                              image_format ="png",
                              layers = "include",
                              transparent = True,
                              scale = 40.0,
                              rotation = -45.0
                              )
export_tiles(levels, 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 export_Tiles 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 a 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. export_Tiles 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.

Note

The default maximum allowed tile count is 100,000. To enable this capability using the Administrator Directory, edit the service, and set the properties exportTilesAllowed = True and maxExportTilesCount = 100000.

Note

In ArcGIS Server 10.2.2 and later versions, exportTiles is supported as an operation of the Map Server. The use of the http://Map_Service/exportTiles/submitJob operation is deprecated. You can provide arguments to the exportTiles operation as defined in the following parameters table:

Parameter

Description

levels

Required string. Specifies the tiled service levels to export. The values should correspond to Level IDs, cache scales. or the resolution as specified in export_by parameter. The values can be comma separated values or a range. Make sure tiles are present at the levels where you attempt to export tiles. Example 1: 1,2,3,4,5,6,7,8,9 Example 2: 1-4,7-9

export_by

Required string. The criteria that will be used to select the tile service levels to export. The values can be Level IDs, cache scales. or the resolution. The default is ‘LevelID’. Values:

levelId | resolution | scale

tile_package

Optional boolean. Allows exporting either a tile package or a cache raster data set. If the value is true, output will be in tile package format, and if the value is false, a cache raster data set is returned. The default value is True.

export_extent

Optional dictionary or string. The extent (bounding box) of the tile package or the cache dataset to be exported. If extent does not include a spatial reference, the extent values are assumed to be in the spatial reference of the map. The default value is full extent of the tiled map service. Syntax:

<xmin>, <ymin>, <xmax>, <ymax>

Example 1: -104,35.6,-94.32,41 Example 2:

{“xmin” : -109.55, “ymin” : 25.76,
“xmax” : -86.39, “ymax” : 49.94,
“spatialReference” : {“wkid” : 4326}}

optimize_for_size

Optional boolean. Use this parameter to enable compression of JPEG tiles and reduce the size of the downloaded tile package or the cache raster data set. Compressing tiles slightly compromises the quality of tiles but helps reduce the size of the download. Try sample compressions to determine the optimal compression before using this feature. The default value is True.

compression=75,

Optional integer. When optimize_for_size=true, you can specify a compression factor. The value must be between 0 and 100. The value cannot be greater than the default compression already set on the original tile. For example, if the default value is 75, the value of compressionQuality must be between 0 and 75. A value greater than 75 in this example will attempt to up sample an already compressed tile and will further degrade the quality of tiles.

area_of_interest

Optional dictionary, Polygon. The area_of_interest polygon allows exporting tiles within the specified polygon areas. This parameter supersedes the exportExtent parameter.

Example:

{ “features”: [{“geometry”:{“rings”:[[[-100,35],
[-100,45],[-90,45],[-90,35],[-100,35]]],
“spatialReference”:{“wkid”:4326}}}]}

asynchronous

Optional boolean. Default False, this value ensures the returns are returned to the user instead of the user having the check the job status manually.

storage_format

Optional string. Specifies the type of tile package that will be created.

tpk - Tiles are stored using Compact storage format. It is supported across the ArcGIS platform.
tpkx - Tiles are stored using CompactV2 storage format, which provides better performance on network shares and cloud store directories. This improved and simplified package structure type is supported by newer versions of ArcGIS products such as ArcGIS Online 7.1, ArcGIS Enterprise 10.7, and ArcGIS Runtime 100.5. This is the default.
Returns

A path to download file is asynchronous is False. 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)

The find method performs the map service find operation.

Parameter

Description

search_text

Required string.The search string. This is the text that is searched across the layers and fields the user specifies.

layers

Optional string. The layers to perform the identify operation on. There are three ways to specify which layers to identify on:

  • top: Only the top-most layer at the specified location.

  • visible: All visible layers at the specified location.

  • all: All layers at the specified location.

contains

Optional boolean. If false, the operation searches for an exact match of the search_text string. An exact match is case sensitive. Otherwise, it searches for a value that contains the search_text provided. This search is not case sensitive. The default is true.

search_fields

Optional string. List of field names to look in.

sr

Optional dict, string, or SpatialReference. The well-known ID of the spatial reference of the input and output geometries as well as the map_extent. If sr is not specified, the geometry and the map_extent are assumed to be in the spatial reference of the map, and the output geometries are also in the spatial reference of the map.

layer_defs

Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.

return_geometry

Optional boolean. If true, the 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 be returned as is and dates will be returned as epoch values.

return_field_name

Optional boolean. If true, field names will be returned instead of field aliases.

transformations

Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different from the map service’s spatial reference. It is an array of transformation elements.

map_range_values

Optional list. Allows you to filter features in the exported map from all layer that are within the specified range instant or extent.

layer_range_values

Optional dictionary. Allows you to filter features for each individual layer that are within the specified range instant or extent. Note: Check range infos at the layer resources for the available ranges.

layer_parameters

Optional list. Allows you to filter the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.

Returns

A dictionary

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> search_results = map_image_item.find(search_text = "Hurricane Data",
                        contains = True,
                        layers = "top",
                        return_geometry = False,
                        max_offset = 100,
                        return_z = True,
                        return_m = False,
                        )
>>> type(search_results)
<Dictionary>
classmethod fromitem(item)

The fromitem method returns the layer at the specified index from a layer Item object.

Parameter

Description

item

Required Item. An item containing layers.

index

Optional int. The index of the layer amongst the item’s layers

Returns

The layer at the specified index.

# Usage Example

>>> layer.fromitem(item="9311d21a9a2047d19c0faaebd6f2cca6", index=3)
generate_kml(save_location, name, layers, options='composite')

The generate_Kml operation is performed on a map service resource. The result of this operation is a KML document wrapped in a KMZ file.

Note

The document contains a network link to the KML Service endpoint with properties and parameters you specify.

Parameter

Description

save_location

Required string. Save folder.

name

Required string. The name of the resulting KML document. This is the name that appears in the Places panel of Google Earth.

layers

Required string. the layers to perform the generateKML operation on. The layers are specified as a comma-separated list of layer ids.

options

Required string. The layer drawing options. Based on the option chosen, the layers are drawn as one composite image, as separate images, or as vectors. When the KML capability is enabled, the ArcGIS Server administrator has the option of setting the layer operations allowed. If vectors are not allowed, then the caller will not be able to get vectors. Instead, the caller receives a single composite image. values: composite, separateImage, nonComposite

Returns

A string to the file path

identify(geometry, map_extent, image_display=None, 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.

Note

Each identified result includes its name, layer ID, layer name, geometry, geometry type, and other attributes of that result as name-value pairs.

Parameter

Description

geometry

Required Geometry or list. The geometry to identify on. The type of the geometry is specified by the geometryType parameter. The structure of the geometries is same as the structure of the JSON geometry objects returned by the API (See Geometry Objects). In addition to the JSON structures, for points and envelopes, you can specify the geometries with a simpler comma-separated syntax.

geometry_type

Required string.The type of geometry specified by the geometry parameter. The geometry type could be a point, line, polygon, or an envelope. Values:

“Point” | “Multipoint” | “Polyline” | “Polygon” | “Envelope”

map_extent

Required string. The extent or bounding box of the map currently being viewed.

sr

Optional dict, string, or SpatialReference. The well-known ID of the spatial reference of the input and output geometries as well as the map_extent. If sr is not specified, the geometry and the map_extent are assumed to be in the spatial reference of the map, and the output geometries are also in the spatial reference of the map.

layer_defs

Optional dict. Allows you to filter the features of individual layers in the exported map by specifying definition expressions for those layers. Definition expression for a layer that is published with the service will be always honored.

time_value

Optional list. The time instant or the time extent of the features to be identified.

time_options

Optional dict. The time options per layer. Users can indicate whether or not the layer should use the time extent specified by the time parameter or not, whether to draw the layer features cumulatively or not and the time offsets for the layer.

layers

Optional string. The layers to perform the identify operation on. There are three ways to specify which layers to identify on:

  • top: Only the top-most layer at the specified location.

  • visible: All visible layers at the specified location.

  • all: All layers at the specified location.

tolerance

Optional integer. The distance in screen pixels from the specified geometry within which the identify operation should be performed. The value for the tolerance is an integer.

image_display

Optional string. The screen image display parameters (width, height, and DPI) of the map being currently viewed. The mapExtent and the image_display parameters are used by the server to determine the layers visible in the current extent. They are also used to calculate the distance on the map to search based on the tolerance in screen pixels.

Syntax:

<width>, <height>, <dpi>

return_geometry

Optional boolean. If true, the 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 be returned as is and dates will be returned as epoch values. The default is False.

return_field_name

Optional boolean. Default is False. If true, field names will be returned instead of field aliases.

transformations

Optional list. Use this parameter to apply one or more datum transformations to the map when sr is different than the map service’s spatial reference. It is an array of transformation elements. Transformations specified here are used to project features from layers within a map service to sr.

map_range_values

Optional list of dictionary(ies). Allows for the filtering features in the exported map from all layer that are within the specified range instant or extent.

layer_range_values

Optional Dictionary. Allows for the filtering of features for each individual layer that are within the specified range instant or extent.

layer_parameters

Optional list of dictionary(ies). Allows for the filtering of the features of individual layers in the exported map by specifying value(s) to an array of pre-authored parameterized filters for those layers. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used instead.

Returns

A dictionary

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> identified = map_image_item.identify(geometry = geom1,
                            geometry_type = "Multipoint",
                            image_display = "width",
                            return_geometry =True,
                            return_z = True,
                            retrun_m = True,
                            return_field_name = True,
                            )
>>> type(identified)
<Dictionary>
property item_info

The item_info method retrieves the service’s item’s information.

Returns

A dictionary

property kml

The kml method retrieves the KML file for the layer.

Returns

A KML file

property legend

The legend property represents a map service’s legend. It returns the legend information for all layers in the service. Each layer’s legend information includes the symbol images and labels for each symbol. Each symbol is an image of size 20 x 20 pixels at 96 DPI. Additional information for each layer such as the layer ID, name, and min and max scales are also included.

Note

The legend symbols include the base64 encoded imageData as well as a url that could be used to retrieve the image from the server.

Returns

Dictionary of legend information

property manager

The manager property returns an instance of MapImageLayerManager class for ArcGIS Online and EnterpriseMapImageLayerManager class for ArcGIS Enterprise which provides methods and properties for administering this service.

property metadata

The metadata property retrieves the service’s XML metadata file

Returns

An XML metadata file

thumbnail(out_path=None)

The thumbnail method retrieves the thumbnail.

Note

If a thumbnail is present, this operation will download the image to local disk.

Returns

A path to the downloaded thumbnail, or None.

MapImageLayerManager

class arcgis.mapping.MapImageLayerManager(url, gis=None, map_img_lyr=None)

Bases: arcgis.gis._GISResource

The MapImageLayerManager class allows administration (if access permits) of ArcGIS Online Hosted Tile Layers or Cached Map Services. A MapImageLayer offers access to the Map Server endpoints that allow you to edit the tile service, update tiles, refresh, and more.

To use this manager off of the MapImageLayer Class, pass in a url ending with /MapServer when instantiating that class.

Note

Map Image Layers are created from Enterprise Services and their manager can be accessed through the EnterpriseMapImageLayerManager.

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.

Parameter

Description

job_id

Required String. The job id to cancel.

delete_tiles(levels, extent=None)

The delete_tiles method deletes tiles from the current cache.

Parameter

Description

levels

Required string, The level to delete. Example, 0-5,10,11-20 or 1,2,3 or 0-5

extent

Optional dictionary, If specified, the tiles within this extent will be deleted or will be deleted based on the service’s full extent.

Returns

A dictionary

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)
>>> map_image_layer = MapImageLayer("<url>", gis)
>>> mil_manager = map_image_layer.manager
>>> deleted_tiles = mil_manager.delete_tiles(levels = "11-20",
                                      extent = {"xmin":6224324.092137296,
                                                "ymin":487347.5253569535,
                                                "xmax":11473407.698535524,
                                                "ymax":4239488.369818687,
                                                "spatialReference":{"wkid":102100}
                                                }
                                      )
>>> type(deleted_tiles)
<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)

The edit_tile_service operation updates a Tile Service’s properties.

Parameter

Description

service_definition

Required String. Updates a service definition.

min_scale

Required float. Sets the services minimum scale for caching.

max_scale

Required float. Sets the services maximum scale for caching.

source_item_id

Required String. The Source Item ID is the GeoWarehouse Item ID of the map service

export_tiles_allowed

Required boolean. exports_tiles_allowed sets the value to let users export tiles

max_export_tile_count

Optional float. max_export_tile_count sets the maximum amount of tiles to be exported from a single call.

Note

The default value is 100000.

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)
>>> map_image_layer = MapImageLayer("<url>", gis)
>>> mil_manager = map_image_layer.manager
>>> mil_manager.edit_tile_service(service_definition = "updated service definition",
                                  min_scale = 50,
                                  max_scale = 100,
                                  source_item_id = "geowarehouse_item_id",
                                  export_tiles_allowed = True,
                                  max_Export_Tile_Count = 10000
                                 )
import_tiles(item, levels=None, extent=None, merge=False, replace=False)

The import_tiles method imports tiles from an Item object.

Before executing this operation, you will need to make certain the following prerequisites are met:

  • Upload the TPK you wish to merge with the existing service, take note of its item ID.

  • Make certain that the uploaded TPK, TPKX item’s tiling scheme matches with the service you wish to import into.

  • The source service LOD’s should include all the LOD’s that are part of the imported TPK item. For example, if the source service has tiles from levels 0 through 10, you can import tiles only within these levels and not above it.

Returns

A dictionary

# USAGE EXAMPLE
>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS
# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)
>>> map_image_layer = MapImageLayer("<url>", gis)
>>> mil_manager = map_image_layer.manager
>>> imported_tiles = mil_manager.import_tiles(item="<item-id>",
                                              levels = "11-20",
                                              extent = {"xmin":6224324.092137296,
                                                        "ymin":487347.5253569535,
                                                        "xmax":11473407.698535524,
                                                        "ymax":4239488.369818687,
                                                        "spatialReference":{"wkid":102100}
                                                        },
                                              merge = True,
                                            replace = True
                                              )
>>> type(imported_tiles)
<Dictionary>
job_statistics(job_id)

Returns the job statistics for the given jobId

refresh()

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.

Parameter

Description

job_id

required string, job to reprocess

code

required string, parameter used to re-run a given jobs with a specific error code: ALL | ERROR | CANCELED

Returns

A boolean or dictionary

update_tiles(levels=None, extent=None, merge=False, replace=False)

The update_tiles method 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

The update_tiles operation is for ArcGIS Online only.

Parameter

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}

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

Dictionary. If the product is not ArcGIS Online tile service, the result will be None.

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)
>>> map_image_layer = MapImageLayer("<url>", gis)
>>> mil_manager = map_image_layer.manager
>>> update_tiles = mil_manager.update_tiles(levels = "11-20",
                                            extent = {"xmin":6224324.092137296,
                                                        "ymin":487347.5253569535,
                                                        "xmax":11473407.698535524,
                                                        "ymax":4239488.369818687,
                                                        "spatialReference":{"wkid":102100}
                                                        }
                                            )
>>> type(update_tiles)
<Dictionary>

EnterpriseMapImageLayerManager

class arcgis.mapping.EnterpriseMapImageLayerManager(url, gis=None, map_img_lyr=None)

Bases: arcgis.gis._GISResource

The EnterpriseMapImageLayerManager class allows administration (if access permits) of ArcGIS Enterprise Map Image Layers and Tile Layers. A MapImageLayer offers access to layer content.

Note

Url must be admin url such as: https://services.myserver.com/arcgis/rest/admin/services/serviceName/MapServer/

change_provider(provider)

Allows for the switching of the service provide and how it is hosted on the ArcGIS Server instance.

Provider parameter options:

  • ArcObjects means the service is running under the ArcMap runtime i.e. published from ArcMap

  • ArcObjects11: means the service is running under the ArcGIS Pro runtime i.e. published from ArcGIS Pro

  • DMaps: means the service is running in the shared instance pool (and thus running under the ArcGIS Pro provider runtime)

Returns

Boolean

delete()

deletes a service from arcgis server

edit(service_dictionary)

To edit a service, you need to submit the complete JSON representation of the service, which includes the updates to the service properties. Editing a service causes the service to be restarted with updated properties.

Parameter

Description

service_dictionary

Required dict. The service JSON as a dictionary.

Returns

boolean

start()

starts the specific service

stop()

stops the specific service

MapTable

class arcgis.mapping.MapTable(url, gis=None, container=None, dynamic_layer=None)

Bases: arcgis.mapping._msl.layer.MapFeatureLayer

The MapTable class represents entity classes with uniform properties.

Note

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 a MapFeatureLayer, except that the rows (Feature) in a table do not have a geometry, and tables ignore any geometry related operation.

classmethod fromitem(item, table_id=0)

The fromitem method creates a MapTable from a GIS Item.

Parameter

Description

item

Required Item object. The type of item should be a MapImageService object.

layer_id

Optional integer. The id of the layer in the Map Service’s Layer. The default is 0.

Returns

A MapTable object

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer, MapTable
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_table = MapFeatureLayer.fromitem(item = map_image_item,
                                                 layer_id = 2)
>>> print(f"{map_table.properties.name:30}{type(map_table)}")
<State Boundaries              <class 'arcgis.mapping.MapTable'>>
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)

The query method queries a Table Layer based on a set of criteria from a sql statement.

Parameter

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.

>>> time_filter=[<startTime>, <endTime>]

Specified as datetime.date, datetime.datetime or timestamp in milliseconds.

>>> import datetime as dt

>>> time_filter = [dt.datetime(2022, 1, 1), dt.dateime(2022, 1, 12)]

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 FeatureSet.

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 FeatureSet. The default is False. This option supersedes the return_ids_only parameter. If return_count_only = True, the response will return both the count and the extent.

order_by_fields

Optional string. One or more field names by which to order the results. Use ASC or DESC for ascending or descending, respectively, following every field to be ordered:

>>> order_by_fields = "STATE_NAME ASC, RACE DESC, GENDER ASC"

group_by_fields_for_statistics

Optional string. One or more field names on which to group results for calculating the statistics.

>>> group_by_fields_for_statiscits = "STATE_NAME, GENDER"

out_statistics

Optional string. The definitions for one or more field-based statistics to be calculated.

Syntax

>>> out_statistics = [
                        {
                          "statisticType": "<count | sum | min | max | avg | stddev | var>",
                          "onStatisticField": "Field1",
                          "outStatisticFieldName": "Out_Field_Name1"
                        },{
                           "statisticType": "<count | sum | min | max | avg | stddev | var>",
                           "onStatisticField": "Field2",
                           "outStatisticFieldName": "Out_Field_Name2"
                          }
                    ]

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, result_offset + ith). 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 maxRecordCount 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.

Note

See Query (Feature Service/Layer) for full explanation of layer properties. Use properties to examine layer properties.

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 or it can use the native SQL of the underlying datastore. The default is none which means the sql_format depends on the 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 the exceededTransferLimit: true property.

When set to false and querying with resultType = ‘tile’, features are not returned when the results include exceededTransferLimit: True. This allows a client to find the resolution in which the transfer limit is no longer exceeded without making multiple calls.

as_df

Optional boolean. If True, the results are returned as a DataFrame instead of a FeatureSet.

range_values

Optional List. Allows you to filter features from the layer that are within the specified range instant or extent.

Syntax

>>> range_values =     [
                        {
                          "name": "range name",
                          "value": <value> or [ <value1>, <value2> ]
                          },
                          {
                            "name": "range name 2",
                            "value": <value> or  [ <value3>, <value4>]
                          }
                        }
                       ]

Note

None is allowed in value-range case – that means infinity

# all features with values <= 1500

>>> range_values = {"name" : "range name",
                     "value :[None, 1500]}

# all features with values >= 1000

>>> range_values = {"name" : "range name",
                    "value" : [1000, None]}

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 parameterInfo allows multiple values, you must pass them in an array.

Note: Check parameterInfos at the layer properties 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 possible parameters is documented at Query (Map Service/Layer)

Returns

A FeatureSet or Panda’s DataFrame containing the Feature objects matching the query, unless another return type is specified, such as count

# USAGE EXAMPLE

>>> from arcgis.mapping import MapImageLayer, MapFeatureLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)

>>> map_image_item = gis.content.get("2aaddab96684405880d27f5261125061")
>>> map_feature_layer = MapFeatureLayer.fromitem(item = map_image_item,
                                                 layer_id = 2)
>>> query_count = map_feature_layer.query(where "1=1",
                            text = "Hurricane Data",
                            units = "esriSRUnit_Meter",
                            return_count_only = True,
                            out_statistics = [
                                                {
                                                "statisticType": "count",
                                                "onStatisticField": "Field1",
                                                "outStatisticFieldName": "Out_Field_Name1"
                                                },
                                                {
                                                "statisticType": "avg",
                                                "onStatisticField": "Field2",
                                                "outStatisticFieldName": "Out_Field_Name2"
                                                }
                                            ],
                            range_values= [
                                    {
                                      "name": "range name",
                                      "value": [None, 1500]
                                      },
                                      {
                                        "name": "range name 2",
                                        "value":[1000, None]
                                      }
                                    }
                                ]
                            )
>>> query_count
<149>

VectorTileLayer

class arcgis.mapping.VectorTileLayer(url, gis=None)

Bases: arcgis.gis.Layer

A Vector Tile Layer is a type of data layer used to access and display tiled data and its corresponding styles. This is stored as an item in ArcGIS and is used to access a vector tile service. Layer data include its name, description, and any overriding style definition.

export_tiles(levels=None, export_extent=None, polygon=None, create_item=False)

Export vector tile layer

Parameter

Description

levels

Optional string.Specifies the tiled service levels to export. The values should correspond to Level IDs. The values can be comma-separated values or a range of values. Ensure that the tiles are present at each specified level.

# Example:

# Comma-separated values
>>> levels=1,2,3,4,5,6,7,8,9

//Range values
>>> levels=1-4, 7-9

export_extent

Optional dictionary of the extent (bounding box) of the vector tile package to be exported. The extent should be within the specified spatial reference. The default value is the full extent of the tiled map service.

# Example:

>>> export_extent = {
                     "xmin": -109.55, "ymin" : 25.76,
                     "xmax": -86.39, "ymax" : 49.94,
                     "spatialReference": {"wkid": 4326}
                    }

polygon

Optional dictionary. Introduced at 10.7. A JSON representation of a polygon, containing an array of rings and a spatialReference.

# Example:

polygon = {
           "rings": [
                     [[6453,16815],[10653,16423],
                     [14549,5204],[-7003,6939],
                     [6453,16815]],[[914,7992],
                     [3140,11429],[1510,10525],
                     [914,7992]]
                    ],
           "spatialReference": {"wkid": 54004}
          }

create_item

Optional boolean. Indicated whether an item will be created from the export (True) or a path to a downloaded file (False). Default is False. ArcGIS Online Only.

Returns

A list of exported item dictionaries or a single path

classmethod fromitem(item)

The fromitem method returns the layer at the specified index from a layer Item object.

Parameter

Description

item

Required Item. An item containing layers.

index

Optional int. The index of the layer amongst the item’s layers

Returns

The layer at the specified index.

# Usage Example

>>> layer.fromitem(item="9311d21a9a2047d19c0faaebd6f2cca6", index=3)
property info

The info property retrieves the relative paths to a list of resource files.

Returns

A list of relative paths

property manager

The manager property returns an instance of VectorTileLayerManager class or EnterpriseVectorTileLayerManager class which provides methods and properties for administering this service.

property styles

The styles property returns styles for vector tiles in Mapbox GL Style specification version 8. The response for this styles resource includes the sprite and glyphs properties, with a relative path to the Vector Tile Sprite and Vector Tile Font resources. It also includes the version property, which represents the version of the style specification.

tile_fonts(fontstack, stack_range)

The tile_fonts method retrieves glyphs in protocol buffer format.

Parameter

Description

fontstack

Required string.

Note

The template url for this font resource is represented in the Vector Tile Style resource.

stack_range

Required string that depict a range. Ex: “0-255”

Returns

Glyphs in PBF format

property tile_map

The tile_map property describes a quadtree of tiles and can be used to avoid requesting tiles that don’t exist in the server. Each node of the tree has an associated tile. The root node (lod 0) covers the entire extent of the data. Children are identified by their position with NW, NE, SW, and SE. Tiles are identified by lod/h/v, where h and v are indexes on a 2^lod by 2^lod grid . These values are derived from the position in the tree. The tree has a variable depth. A node doesn’t have children if the complexity of the data in the associated tile is below a threshold. This threshold is based on a combination of number of features, attributes, and vertices.

tile_sprite(out_format='sprite.json')

The tile_sprite resource retrieves sprite images and metadata.

Parameter

Description

out_format

Optional string. Default is “sprite.json”.

Values: sprite.json | sprite.png | sprite@2x.png

Returns

Sprite image and metadata.

vector_tile(level, row, column)

The vector_tile method represents a single vector tile for the map.

Note

The bytes for the tile at the specified level, row and column are returned in PBF format. If a tile is not found, an error is returned.

Parameter

Description

level

Required string. A level number as a string.

row

Required string. Number of the row that the tile belongs to.

column

Required string. Number of the column that tile belongs to.

Returns

Bytes in PBF format

VectorTileLayerManager

class arcgis.mapping.VectorTileLayerManager(url, gis=None, vect_tile_lyr=None)

Bases: arcgis.gis._GISResource

The VectorTileLayerManager class allows administration (if access permits) of ArcGIS Online Hosted Vector Tile Layers. A Hosted Vector Tile Service is published through a Feature Layer and these methods can only be applied to such Vector Tile Services. A VectorTileLayer offers access to layer content.

Note

Url must be admin url such as: https://services.myserver.com/arcgis/rest/admin/services/serviceName/VectorTileServer/

cancel_job(job_id)

The cancel operation supports cancelling a job while update tiles is running from a hosted feature service. The result of this operation is a response indicating success or failure with error code and description.

delete_job(job_id)

This operation deletes the specified asynchronous job being run by the geoprocessing service. If the current status of the job is SUBMITTED or EXECUTING, it will cancel the job. Regardless of status, it will remove all information about the job from the system. To cancel a job in progress without removing information, use the Cancel Job operation.

delete_tiles()

The delete_tiles method deletes tiles from the current cache.

Note

The delete_tiles operation is for ArcGIS Online only and can only be used for a Vector Tile Layer published from a service directory.

Returns

A dictionary

# USAGE EXAMPLE

>>> from arcgis.mapping import VectorTileLayer
>>> from arcgis.gis import GIS

# connect to your GIS
>>> gis = GIS(url, username, password)

>>> vector_layer_item = gis.content.get('abcd_item-id')
>>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item)
>>> vtl_manager = vector_tile_layer.manager
>>> deleted_tiles = vtl_manager.delete_tiles()
>>> type(deleted_tiles)
edit_tile_service(source_item_id=None, export_tiles_allowed=None, min_scale=None, max_scale=None, max_export_tile_count=None, layers=None, cache_max_age=None, max_zoom=None)

The edit operation enables editing many parameters in the service definition as well as the source_item_id which can be found by looking at the Vector Tile Layer’s related items.

Parameter

Description

source_item_id

Optional String. The Source Item ID is the GeoWarehouse Item ID of the tile service.

export_tiles_allowed

Optional boolean. exports_tiles_allowed sets the value to let users export tiles

min_scale

Optional float. Sets the services minimum scale for caching. At the moment this parameter can only be set if the Vector Tile Layer was published through a service directory.

max_scale

Optional float. Sets the services maximum scale for caching. At the moment this parameter can only be set if the Vector Tile Layer was published through a service directory.

max_export_tile_count

Optional int. max_export_tile_count sets the maximum amount of tiles to be exported from a single call.

layers

Optional list of dictionaries. Each dict representing a layer.

Syntax Example:

layers = [{
“name”: “Layer Name”,
“id”: 1159321,
“layerId”: 0,
“tableName”: “tableName”,
“type”: “Feature Layer”,
“xssTrustedFields”: “”
}]

cache_max_age

Optional int. The maximum cache age. At the moment this parameter can only be set if the Vector Tile Layer was published through a feature service.

max_zoom

Optional int. The maximum zoom level. At the moment this parameter can only be set if the Vector Tile Layer was published through a feature service.

# USAGE EXAMPLE

>>> from arcgis.mapping import VectorTileLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the tile layer item
>>> gis = GIS(url, username, password)

>>> vector_layer_item = gis.content.get('abcd_item-id')
>>> source_item_id = vector_tile_item.related_items(rel_type="Service2Data", direction="forward")[0]["id"]
>>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item)
>>> vtl_manager = vector_tile_layer.manager
>>> vtl_manager.edit_tile_service(
                                min_scale = 50,
                                max_scale = 100,
                                source_item_id = source_item_id,
                                export_tiles_allowed = True,
                                max_Export_Tile_Count = 10000
                                )
job_statistics(job_id)

The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.

jobs()

The tile service job summary (jobs) resource represents a summary of all jobs associated with a vector tile service. Each job contains a jobid that corresponds to the specific jobid run and redirects you to the Job Statistics page.

rebuild_cache()

The rebuild_cache operation update the vector tile layer cache to reflect any changes made to the feature layer used to publish this vector tile layer. The results of the operation is a response indicating success, which redirects you to the Job Statistics page, or failure.

refresh()

The refresh operation clears and refreshes the service cache.

rerun_job(code, job_id)

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.

Parameter

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

A boolean or dictionary

status()

The status operation returns a dictionary indicating whether a service is started (available) or stopped.

swap(target_service_name)

The swap operation replaces the current service cache with an existing one.

Note

The swap operation is for ArcGIS Online only and can only be used for a Vector Tile Layer published from a service directory.

Parameter

Description

target_service_name

Required string. Name of service you want to swap with.

Returns

Dictionary indicating success or error

update_tiles(merge_bundle=False)

The update_tiles operation supports updating the cooking extent and cache levels in a Hosted Vector Tile Service. The results of the operation is a response indicating success and a url to the Job Statistics page, or failure.

It is recommended to use the rebuild_cache method when your layer has been published through a Feature Layer since edits require regeneration of the tiles.

Parameter

Description

merge_bundle

Optional bool. Default is False. This parameter will only be set if the Vector Tile Layer has been published through a service directory.

Returns

Dictionary. If the product is not ArcGIS Online tile service, the result will be None.

# USAGE EXAMPLE

>>> from arcgis.mapping import VectorTileLayer
>>> from arcgis.gis import GIS

# connect to your GIS and get the web map item
>>> gis = GIS(url, username, password)
>>> vector_layer_item = gis.content.get('abcd_item-id')
>>> vector_tile_layer = VectorTileLayer.fromitem(vector_layer_item)
>>> vtl_manager = vector_tile_layer.manager
>>> update_tiles = vtl_manager.update_tiles()
>>> type(update_tiles)
<Dictionary>

EnterpriseVectorTileLayerManager

class arcgis.mapping.EnterpriseVectorTileLayerManager(url, gis=None, vect_tile_lyr=None)

Bases: arcgis.gis._GISResource

The EnterpriseVectorTileLayerManager class allows administration (if access permits) of ArcGIS Enterprise hosted vector tile layers. A Hosted Vector Tile Service is published through a Feature Layer and these methods can only be applied to such Vector Tile Services. A VectorTileLayer offers access to layer content.

Note

Url must be admin url such as: https://services.myserver.com/arcgis/server/admin/services/serviceName.VectorTileServer/

change_provider(provider)

The changeProvider operation updates an individual service to use either a dedicated or a shared instance type. When a qualified service is published, the service is automatically set to use shared instances.

When using this operation, services may populate other provider types as values for the provider parameter, such as ArcObjects and SDS. While these are valid provider types, this operation does not support changing the provider of such services to either ArcObjects11 or DMaps. Services with ArcObjects or SDS as their provider cannot change their instance type.

Parameter

Description

provider

Optional String. Specifies the service instance as either a shared (“DMaps”) or dedicated (“ArcObjects11”) instance type. These values are case sensitive.

Returns

Boolean

delete()

This operation deletes an individual service, stopping the service and removing all associated resources and configurations.

edit(service_dictionairy)

This operation edits the properties of a service. To edit a service, you need to submit the complete JSON representation of the service, which includes the updates to the service properties. Editing a service can cause the service to be restarted with updated properties.

The JSON representation of a service contains the following four sections:

  • Service description properties—Common properties that are shared by all services. These properties typically identify a specific service.

  • Service framework properties—Properties targeted toward the framework that hosts the GIS service. They define the life cycle and load balancing of the service.

  • Service type properties—Properties targeted toward the core service type as seen by the server administrator. Since these properties are associated with a server object, they vary across the service types.

  • Extension properties—Represent the extensions that are enabled on the service.

Note

The JSON is submitted to the operation URL as a value of the parameter service. You can leave out the serviceName and type parameters in the JSON representation. Any other properties that are left out are not persisted by the server.

Parameter

Description

service_dictionary

Required dict. The JSON representation of the service and the properties that have been updated or added.

Example:

{
“serviceName”: “RI_Fed2019_WM”,
“type”: “VectorTileServer”,
“description”: “”,
“capabilities”: “TilesOnly,Tilemap”,
“extensions”: [],
“frameworkProperties”: {},
“datasets”: []
}
Returns

boolean

rebuild_cache(min_scale=None, max_scale=None)

The rebuild_cache operation updates the vector tile layer cache to reflect any changes made. The results of the operation is the url to the vector tile service once it is done rebuilding.

Parameter

Description

min_scale

Optional Float. Represents the minimum scale of the tiles. If nothing is provided, default value is used.

max_scale

Optional Float. Represents the maximum scale of the tiles. If nothing is provided, default value is used.

start()

This operation starts a service and loads the service’s configuration.

stop()

This operation stops all instances of a service. Once a service is stopped, it cannot process any incoming requests. Performing this operation will stop the respective servers, terminating all pods that run this service.

Utility Functions for Mapping

export_map

arcgis.mapping.export_map(web_map_as_json=None, format='PDF', layout_template='MAP_ONLY', gis=None, **kwargs)

The export_map function takes the state of the WebMap object (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.

Note

The export_map tool is shipped with ArcGIS Server to support web services for printing, including the preconfigured service named PrintingTools.

Parameter

Description

web_map_as_json

Web Map JSON along with export options. See the Export Web Map Specifications for more information on structuring 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 get_layout_templates function

gis

The GIS to use for printing. Optional parameter. When not specified, the active GIS will be used.

Returns:

A dictionary with URL to download the output file.

create_colormap

arcgis.mapping.create_colormap(color_list, name='temp_cmap', bins=256)

The create_colormap function is a simple function that allows a user to make a matplotlib LinearSegmentedColormap object based on a custom assortment of colors. Accepts a list of RGB/RGB + alpha arrays. This function is great for visualizing potential color schemes to be used in mapping.

Parameter

Description

color_list

Required list. List items must be of the format [R, G, B], where R, G, and B represent values from 0 to 255, or any other format where the first 3 values represent RGB values in bytes.

name

Optional string. The name of the new colormap item. Defaults to “temp_cmap”.

bins

Optional int. The number of bins (or uniquely retrievable colors) the new colormap has. Defaults to 256.

get_layout_templates

arcgis.mapping.get_layout_templates(gis=None)

The get_layout_templates method returns the content of the GIS object’s layout templates.

Note

The layout templates are formatted as a dictionary.

Note

See the Get Layout Templates Info Task for additional help on the get_layout_templates method.

Parameter

Description

gis

Optional GIS object. The GIS on which get_layout_templates runs.

Note

If gis is not specified, the active GIS is used.

Returns:

output_json - The layout templates as Python dictionary

Symbology

The Symbology class generates Symbol Types for the GIS object.

arcgis.mapping.symbol.create_symbol(geometry_type, symbol_type=None, symbol_style=None, colors=None, **kwargs)

The create_symbol method generates a Symbol from a given set of parameters.

create_symbol creates either a Picture, Text, Cartographic, or Simple Symbol based on a given set of parameters.

Note

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, it’s 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.

Parameter

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.

Parameter

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.

Parameter

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.

Parameter

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)

The display_colormaps method 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.

Note

``display_colormaps is a variation of the colormaps reference page for matplotlib.

arcgis.mapping.symbol.show_styles(geometry_type)

The show_styles method retrieves the available styles for a given geometry type as a Pandas dataframe.

Returns

A Pandas Dataframe

generate_simple

arcgis.mapping.renderer.generate_simple(geometry_type, sdf_or_series=None, label=None, colors=None, alpha=1, **symbol_args)

Generates a simple renderer. Accepts certain symbol arguments used in mapping.symbol.create_symbol(). Used in spatial.plot() and generate_renderer().

Parameter

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 Pandas Series. The spatial dataset to render.

label

Optional string. Name of the layer in the TOC/Legend.

colors

Optional string/list/object. Color mapping. Can be array of RGB values, the string name of a colormap, the hex string of a color, or a palettable object. Defaults to ‘jet’ colormap.

alpha

Optional float. The 0 to 1 alpha value of the color used to render, if the input for ‘colors’ is a colorbrewer JS array or palettable object with no cstep (all other forms of color input have alpha accounted for in bytes form). Defaults to 1.

Symbol 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.

cstep

Int. If colors argument is the name of a colormap or a palettable object, the colorstep value for the colormap. Range is 0-255.

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.

Returns

A dictionary of the renderer.

generate_heatmap

arcgis.mapping.renderer.generate_heatmap(sdf_or_series=None, colors=None, alpha=1, blur_radius=10, field=None, max_intensity=10, min_intensity=0, ratio=0.01, stops=3, show_none=False)

Generates a heatmap renderer. Used in spatial.plot() and generate_renderer().

Parameter

Description

sdf_or_series

Optional Pandas Series. The spatial dataset to render.

colors

Optional string/list/object. Color mapping. Can be array of RGB values, the string name of a colormap, the hex string of a color, or a palettable object. Defaults to ‘jet’ colormap.

alpha

Optional float. The 0 to 1 alpha value of the color used to render, if the input for ‘colors’ is a colorbrewer JS array or palettable object with no cstep (all other forms of color input have alpha accounted for in bytes form). Defaults to 1.

blur_radius

Optional int. The radius (in pixels) of the circle over which the majority of each point’s value is spread. Defaults to 10.

field

Optional string. 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

Optional int. The pixel intensity value which is assigned the final color in the color ramp. Defaults to 10.

min_intensity

Optional int. The pixel intensity value which is assigned the initial color in the color ramp. Defaults to 0.

ratio

Optional float. A number between 0-1. Describes what portion along the gradient the colorStop is added. Defaults to 0.01

stops

Optional int. The amount of color stops created for the renderer. Default and minimum is 3.

show_none

Optional boolean. Determines the alpha value of the base color for the heatmap. Setting this to True covers an entire map with the base color of the heatmap. Default is False.

Returns

A dictionary of the renderer.

generate_unique

arcgis.mapping.renderer.generate_unique(geometry_type, sdf_or_series=None, colors=None, alpha=1, **symbol_args)

Generates a unique renderer. Define an attribute field using a field1 argument. Accepts symbol arguments used in mapping.symbol.create_symbol(). Used in spatial.plot() and generate_renderer().

Parameter

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 Pandas Series. The spatial dataset to render.

colors

Optional string/list/object. Color mapping. Can be array of RGB values, the string name of a colormap, the hex string of a color, or a palettable object. Defaults to ‘jet’ colormap.

alpha

Optional float. The 0 to 1 alpha value of the color used to render, if the input for ‘colors’ is a colorbrewer JS array or palettable object with no cstep (all other forms of color input have alpha accounted for in bytes form). Defaults to 1.

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…}
}
Returns

A dictionary of the renderer.

generate_classbreaks

arcgis.mapping.renderer.generate_classbreaks(sdf_or_series=None, geometry_type=None, colors=None, alpha=1, **symbol_args)

Generates a classbreaks renderer. Define the attribute field using a field argument. Accepts symbol arguments used in mapping.symbol.create_symbol(). Used in spatial.plot() and generate_renderer().

Parameter

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 Pandas Series. The spatial dataset to render.

colors

Optional string/list/object. Color mapping. Can be array of RGB values, the string name of a colormap, the hex string of a color, or a palettable object. Defaults to ‘jet’ colormap.

alpha

Optional float. The 0 to 1 alpha value of the color used to render, if the input for ‘colors’ is a colorbrewer JS array or palettable object with no cstep (all other forms of color input have alpha accounted for in bytes form). Defaults to 1.

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.

Returns

A dictionary of the renderer.

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 Pandas Series. 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 or single RGB + alpha color array. For a unique renderer, a list of color arrays or colormaps can be given. For heatmaps, list specific RGB colorstops, give the name of a colormap, or provide a list of colormaps.

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.

show_none

Boolean. Determines the alpha value of the base color for the heatmap. Setting this to True covers an entire map with the base color of the heatmap. Default is False.

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:

Parameter

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

A dictionary of the renderer.

visual_variables

arcgis.mapping.renderer.visual_variables(geometry_type, sdf_or_list, **kwargs)

The visual_variables function is used to create visual variables for the GIS object.

visual_variables allows developers to take a deep dive into developing custom renderer. Here a user/developer can create transparency, size information, and other rules to improve the overall feel and look of spatial information on a map.

Note

Each type of information is detailed in the tables below.

Optional variables

Description

trans_info_field

Attribute field used for setting the transparency of a feature if no trans_value_exp is provided.

trans_norm_field

Attribute field used to normalize the data.

trans_stops

An array of transparency stop objects.

trans_value_exp

An Arcade expression evaluating to a number.

trans_exp_title

The title identifying and describing the associated Arcade expression as defined in the valueExpression property.

Size Info Visual Variable

The size Info visual variable defines how size is applied to features based on the values of a numeric field attribute. The minimum and maximum values of the data should be indicated along with their respective size values. You must specify minSize and maxSize or stops to construct the size ramp. All features with values falling in between the specified min and max data values (or stops) will be scaled proportionally between the provided min and max sizes.

Parameter

Description

si_field

Attribute field used for size rendering if no si_expression is provided.

si_max_data_value

The maximum data value.

si_max_size

Specifies the largest marker size to use at any given map scale. Can be either a fixed number or object, depending on whether the user chose a fixed range or not.

si_min_data_value

The minimum data value.

si_min_size

Specifies the smallest marker size to use at any given map scale. Can be either a fixed number or object, depending on whether the user chose a fixed range or not.

si_norm_field

Attribute field used to normalize the data.

si_stops

An array of objects that defines the thematic size ramp in a sequence of data or expression stops.

si_target

Only used when sizeInfo is used for polygon outlines. Value of this property must be outline

si_expression

An Arcade expression evaluating to a number

si_expression_title

the title identifying and describing the associated Arcade expression

si_value_unit

A string value indicating the required unit of measurement.

Rotation Info Visual Variable

A rotation variable is a visual variable that defines the rotation of a symbol based on a numeric data value returned from a field or expression. This value is typically used to rotate symbols that indicate directionality.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.