Update ArcGIS Online WebMap Extent Based on Feature Geometry with the ArcGIS API for Python

If you have ever had to reset the extent of a WebMap after it has been let out in the wild for a while, then this workflow is for you. Here, we will focus in updating the extent for one WebMap, but you could certainly iterate through as many as required and update each extent individually as you go along. Please note, that this workflow is for the latest Map Viewer in ArcGIS Online (AGOL) and not for the Classic Viewer.

Below is a WebMap zoomed to the extent of Ireland with some layers added. 

The script below will alter the extent of the WebMap to zoom to Galway on the west- coast of the island. You will need to fill in the 

  • wm_item_id on line 10
  • the layer title on line 20,
  • and the SQL clause on line 26.
				
					from arcgis.gis import GIS
from arcgis.mapping import WebMap
from arcgis.geometry import Geometry
from arcgis.features import FeatureLayer

## Access AGOL
agol = GIS("home")

## the ITEM ID of the WebMap to update
wm_item_id = "WM_ITEM_ID"

## get the WebMap as an Item object
wm_item = agol.content.get(wm_item_id)

## create a WebMap object from the Item object
webmap = WebMap(wm_item)

## get the url of the layer in the WebMap that we want to zoom to the
## extent of
layer_url = webmap.get_layer(title="ENTER LYR TITLE").url

## get this layer as a FeatureLayer from the Feature Service
fl = FeatureLayer(layer_url, agol)

## Query the layer to return the feature you want to zoom to.
f = fl.query(where="ENTER SQL CLAUSE")

## get the minimum bounding of that feature as an envelope
bbox = Geometry(f.features[0].geometry).envelope

## create a dictionary as per below
extent = {
    "viewpoint": {
        "targetGeometry": bbox
    }
}

## update/add and initialState property to the WebMap
webmap.definition["initialState"] = extent

## create a dictionary of the new WebMap intem properties
item_properties = {"text":webmap.definition}

## update the WebMap to reflect the new properties
## run the script and then refresh your WebMap to test
wm_item.update(item_properties=item_properties)
				
			

After running the script and refreshing the WebMap, we can see that the extent of the WebMap has altered to the area of interest.

Leave a Comment

Your email address will not be published. Required fields are marked *