Using the map widget

arcgis.mapping module

The arcgis.mapping module contains classes and functions to represent and interact with web maps, scenes, and certain layer types such as map image and vector tiles. In this page we will observe how to visualize maps, scenes and layers using the map widget in Jupyter notebook environment.

Using the map widget

The GIS object includes a map widget for displaying geographic locations, visualizing GIS content, as well as the results of your analysis. To use the map widget, call gis.map() and assign it to a variable, that you can then query to bring up the widget in the notebook:

import arcgis
from arcgis.gis import GIS
# Create a GIS object, as an anonymous user for this example
gis = GIS()
# Create a map widget
map1 = gis.map('Paris') # Passing a place name to the constructor
                        # will initialize the extent of the map.
map1

Setting the map properties

Zoom level

The map widget has several properties that you can query and set, such as its zoom level, basemap, height, etc:

map1.zoom
2.0

Assigning a value to the zoom property will update the widget.

map1.zoom = 10

You can also set rotation in 2D mode. This can also be achieved by right-clicking and dragging on the map.

map1.rotation = 45

Your notebook can have as many of these widgets as you wish. Let us create another map widget and modify some of its properties.

Map center

The center property reveals the coordinates of the center of the map.

map2 = gis.map() # creating a map object with default parameters
map2

image.png

map2.center
{'spatialReference': {'latestWkid': 3857, 'wkid': 102100},
 'x': 0,
 'y': 1.30385160446167e-08}

If you know the latitude and longitude of your place of interest, you can assign it to the center property.

map2.center = [34,-118] # here we are setting the map's center to Los Angeles

You can use geocoding to get the coordinates of place names and drive the widget. Geocoding converts place names to coordinates and can be used using arcgis.geocoding.geocode() function.

Let us geocode Times Square, NY and set the map's extent to the geocoded location's extent.

location = arcgis.geocoding.geocode('Times Square, NY', max_locations=1)[0]
map2.extent = location['extent']

Basemaps

Basemap are layers on your map over which all other operational layers that you add are displayed. Basemaps typically span the full extent of the world and provide context to your GIS layers. It helps viewers understand where each feature is located as they pan and zoom to various extents.

Your map can have a number of different basemaps. To see what basemaps are included with the widget, query the basemaps property

map3 = gis.map()
map3.basemaps
['dark-gray',
 'dark-gray-vector',
 'gray',
 'gray-vector',
 'hybrid',
 'national-geographic',
 'oceans',
 'osm',
 'satellite',
 'streets',
 'streets-navigation-vector',
 'streets-night-vector',
 'streets-relief-vector',
 'streets-vector',
 'terrain',
 'topo',
 'topo-vector']

You can assign any one of the supported basemaps to the basemap property to change the basemap. For instance, you can change the basemap to the dark gray vector basemap as below:

map3.basemap = 'dark-gray-vector'
map3

image.png

Query the basemap property to find what the current basemap is

map3.basemap
'dark-gray-vector'

Let us animate a new map widget by cycling through basemaps and assigning it to the basemap property of the map widget.

map4 = gis.map('New York City, NY')
map4

import time

for basemap in map4.basemaps:
    map4.basemap = basemap
    time.sleep(3)

3D Mode

The map widget also includes support for 3D mode! You can specify the 'mode' parameter through gis.map(mode="foo"), or by setting the mode property of any instatiated map object. Run the below cell:

from arcgis.gis import GIS
gis = GIS()
usa_map = gis.map('USA', zoomlevel=4, mode="3D") #Notice `mode="3D"`
usa_map

Just like 2D mode, you can pan by click-and-drag with the left mouse button, and you can zoom with the mouse wheel. In 3D mode, click-and-drag with the right mouse button modifies the tilt field and the heading field.

tilt is a number from 0-90: 0 represents a top-down 'birds-eye' view, while 90 represents being completely parallel to the ground, facing the horizon.

It's important to note that 2D mode uses rotation to specify the number of angles clockwise from due north, while 3D mode uses heading to specify the number of degrees counterclockwise of due north. See the API reference for more information.

Try running the below two cells, and replace them with your own values!

usa_map.tilt = 45
usa_map.heading = 45

Read more about 3D mode by reading the advanced map widget useage guide page, or by reading the API reference.

Adding layers to the map

An important functionality of the map widget is its ability to add and render GIS layers. To a layer call the add_layer() method and pass the layer object as an argument.

# Log into to GIS as we will save the widget as a web map later
gis = GIS("https://www.arcgis.com", "arcgis_python", "P@ssword123")
usa_map = gis.map('USA', zoomlevel=4)  # you can specify the zoom level when creating a map
usa_map

Next, search from some layers to add to the map

flayer_search_result = gis.content.search("owner:esri","Feature Layer", outside_org=True)
flayer_search_result
[<Item title:"USA Census Populated Places" type:Feature Layer Collection owner:esri>,
 <Item title:"2019 USA Traffic Counts" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Offshore Pipelines (Mature Support)" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Senate" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Shipping Fairways Lanes Zones (Mature Support)" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Drilling Platforms" type:Feature Layer Collection owner:esri>,
 <Item title:"World Exclusive Economic Zone Boundaries" type:Feature Layer Collection owner:esri>,
 <Item title:"Location Tracking" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Anchorage Areas (Mature Support)" type:Feature Layer Collection owner:esri>,
 <Item title:"USA Territorial Sea Boundary (Mature Support)" type:Feature Layer Collection owner:esri>]

Adding Item objects to the map

You can add Item objects to a map by passing it to the add_layer() method.

world_timezones_item = gis.content.get('312cebfea2624e108e234220b04460b8')
usa_map.add_layer(world_timezones_item)

Adding layer objects to the map

You can add a number of different layer objects such as FeatureLayer, FeatureCollection, ImageryLayer, MapImageLayer to the map. You can add a FeatureLayer as shown below:

world_countries_item = gis.content.get('ac80670eb213440ea5899bbf92a04998')
world_countries_layer = world_countries_item.layers[0]
world_countries_layer
<FeatureLayer url:"https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/World_Countries/FeatureServer/0">
usa_map.add_layer(world_countries_layer, options={'opacity':0.4})

Adding layers with custom symbology

While calling the add_layer() method, you can specify a set of renderer instructions as a dictionary to the options parameter. The previous cell shows how you can set the transparency for a layer. The opacity value ranges from 0 - 1, with 0 being fully transparent and 1 being fully opaque.

You can make use of the "smart mapping" capability to render feature layers with symbology that varies based on an attribute field of that layer. The cell below adds the 'USA Freeway System' layer to the map and changes the width of the line segments based on the length of the freeway.

freeway_feature_layer = gis.content.get('51275617f1274103b81d99cd0ad94a40').layers[0]
usa_map.add_layer(freeway_feature_layer, {"renderer":"ClassedSizeRenderer", "field_name": "DIST_MILES"})

Refer to the guide on smart mapping to learn more about this capability.

Adding imagery layers

Similar to FeatureLayers, you can also add ImageryLayers and imagery layer items. You can also specify either a built-in raster function or a custom one for rendering.

landsat_item = GIS().content.search("Landsat 8 Views", "Imagery Layer", max_items=2)[0]
landsat_item
Pansharpened Landsat
Landsat 8 OLI, 15m multitemporal PanSharpened Natural Color images. This imagery layer is sourced from the Landsat on AWS collections and is updated daily with new imagery.Imagery Layer by esri
Last Modified: May 03, 2018
0 comments, 17,822 views
usa_map.add_layer(landsat_item)

Listing the layers added to the map

You can list the layers added to be map using the layers property.

usa_map.layers
[{'type': 'FeatureLayer',
  'url': 'https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/World_Time_Zones/FeatureServer/0?token=_M4Vg2lmNAFmJtmzi_jqtVFDsRK5kAPOOPpgoalkq5oR14r6wTv5IP0gplo81revxb7t0DbDh3GHCNU8Coihs5jeLvIYFGBZI0ZIW_KdZ3no1fzefPc1fG8GHIzFhsc9mTxL0cDr9e0YVMChz86M_E7_gFvpnWiP_rQGmMhsZmo.',
  'options': {},
  '_hashFromPython': '274241533'},
 {'type': 'FeatureLayer',
  'url': 'https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/World_Countries/FeatureServer/0?token=EVOuXYldA35W1h5Zqdzhi_kvBjc94qxXtVR6sOY9OOVmsd9L16FEjIeKv-TnpmJCAEl_Ej_MOB1VdcnaVjSMAYciG4VwgfS4BzQATpC89Rm8rmGKEaDW6dV0KEC8VRPynMF3mDdU9XeSvJ_fQtoMigWKWYUWlost6DOhgRd_AXk.',
  'options': {'opacity': 0.4},
  '_hashFromPython': '-9223372036580569628'},
 {'type': 'FeatureLayer',
  'url': 'https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Freeway_System/FeatureServer/1?token=eN8zkcL7j3pAMmAmFB91PcbwEMQrNq_AAay-U4cuRTq6lwmzrqPeNzXJ1IHUAXYPq-KsuBbboH0z9QFgLImkqGSgjE9BE8SU2uzx7NjSNEAYhv5EGcK0mBU8pGErGrJYM5Gljlje8h8u6IukqJYc9X8pDUl0c0QIUzSsaqEGxt8.',
  'options': {'renderer': 'ClassedSizeRenderer', 'field_name': 'DIST_MILES'},
  '_hashFromPython': '-9223372036580572570'},
 {'type': 'ImageryLayer',
  'url': 'https://landsat2.arcgis.com/arcgis/rest/services/Landsat/PS/ImageServer',
  'uses_gbl': False,
  'options': {},
  '_hashFromPython': '291514376'}]

Removing layers from the map

To remove one or more layers, call the remove_layers() method and pass a list of layers that you want removed. To get a list of valid layers that can be removed, call the layers property as shown in the previous cell.

The code below shows how to remove the USA freeways layer

usa_map.remove_layers(layers=[landsat_item])
True

To remove all layers, call the remove_layers() method with any parameters.

Zooming to Layer

To zoom to one or more layers, call the zoom_to_layer() method and pass a layer or list of layers that you want to snap your map to. The supplied item can be a single or a list of Items, layers, DataFrame, FeatureSet, FeatureCollection.

The code below shows how to zoom to a single layer or multiple items.

# Zoom to a single layer
usa_map.zoom_to_layer(world_countries_layer)

# Zoom to multiple items
usa_map.zoom_to_layer([world_timezones_item, world_countries_layer.query().sdf])

Drawing graphics on the map

You can draw or sketch graphics on the map using the draw() method. For instance, you can draw and annotate rectangles, ellipses, arrow marks etc. as shown below:

usa_map.draw('rectangle')

Now scroll to the map and draw a rectangle.

usa_map.draw('circle')

Scoll back to the map again and place an 'up arrow' below Los Angeles. Refer to the API reference documentation for draw to get the list of supported shapes that you can sketch on the map.

Drawing FeatureSet objects on the map

In addition to sketches, you can send FeatureSet objects to the draw() method. This capability comes in handy as you can get a FeatureSet object through various different operations using the Python API. For instance, you can get results of a geocoding operation as a FeatureSet, results of a query() operation on a FeatureLayer as a FeatureSet that can you visualize on the map using the draw() method.

The snippet below geocodes the locations of a few capitol buildings in the USA.

from arcgis.geocoding import geocode
usa_extent = geocode('USA')[0]['extent']
usa_extent
{'xmin': -146.08761918999994,
 'ymin': -7.2742968439999345,
 'xmax': -52.74161918999994,
 'ymax': 84.9}
usa_capitols_fset = geocode('Capitol', search_extent=usa_extent, max_locations=10, as_featureset=True)
usa_capitols_fset
<FeatureSet> 10 features

Drawing with custom symbols

While drawing a graphic, you can specify a custom symbol. Users of the Python API can make use of a custom symbol selector web app and pick a symbol for point layers. For instance, you can pick a business marker symbol for the capitol buildings as shown below:

capitol_symbol = {"angle":0,"xoffset":0,"yoffset":0,"type":"picture-marker",
                  "url":"http://static.arcgis.com/images/Symbols/PeoplePlaces/esriBusinessMarker_57.png",
                  "contentType":"image/png","width":24,"height":24}

usa_map.draw(usa_capitols_fset, symbol=capitol_symbol)

Clearing the drawn graphics

You can clear all drawn graphics from the map by calling the clear_graphics() method.

usa_map.clear_graphics()

Saving the map as a web map

Starting with the Python API version 1.3, you can save the map widget as a web map in your GIS. This process persistes all the basemaps, layers added with or without your custom symbology including smart mapping, pop-ups, extent, graphics drawn with or without custom symbols as layers in your web map.

To save the map, call the save() method. This method creates and returns a new Web Map Item object. As parameters, you can specify all valid Item properties as shown below:

webmap_properties = {'title':'USA time zones and capitols',
                    'snippet': 'Jupyter notebook widget saved as a web map',
                    'tags':['automation', 'python']}

webmap_item = usa_map.save(webmap_properties, thumbnail='./webmap_thumbnail.png', folder='webmaps')
webmap_item
USA time zones and capitols
Jupyter notebook widget saved as a web mapWeb Map by arcgis_python
Last Modified: August 15, 2018
0 comments, 0 views

You can use this web map back in the notebook, or in any ArcGIS app capabale of rendering web maps. To learn how you can use this read this web map using the Python API, refer to the guide titled working with web maps and scenes

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