Add/Update Feature Layer Filter in ArcGIS Online with the ArcGIS API For Python

We are going to look at how we update/apply a filter for a layer in a WebMap in ArcGIS Online using the ArcGIS API for Python. The commented codeblock below will achieve this.

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

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

## access the WebMap Item
wm_item = agol.content.get("WebMap_Item_ID")

## create a WebMap object
webmap = WebMap(wm_item)

## get the layer of interest
lyr = webmap.get_layer(title="Name of layer as it appears in the WebMap")
## set the filter
lyr.layerDefinition.definitionExpression = "FIELDNAME = 'attribute'" # for text field

## update the webmap

Let’s see it in action. Below is a map in ArcGIS Online currently showing the county boundaries of Ireland. 

We will run the previous code snippet providing a WebMap_Item_ID and setting the title parameter for the get_layer() method to County Boundaries (the name of the layer), and we will set the expression as per below.

					## get the layer of interest
lyr = webmap.get_layer(title="County Boundaries")
## set the filter
lyr.layerDefinition.definitionExpression = "COUNTY = 'KILDARE'"

We can see that the filter has been applied (when I refreshed the map).

Note: you might get the following error!

					AttributeError: 'PropertyMap' instance has no attribute 'layerDefinition'


If this occurs try the below as a replacement. In fact, I would nearly suggest using this dictionary style approach over dot notation. 

					## set the filter
lyr.layerDefinition["definitionExpression"] = "COUNTY = 'KILDARE'"

Leave a Comment

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