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
webmap.update()
Let’s see it in action. Below is a map in ArcGIS Online currently showing the county boundaries of Ireland.
![](https://finaldraftmapping.com/wp-content/uploads/2024/02/fdm_blog_no_filter-1024x530.png)
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).
![](https://finaldraftmapping.com/wp-content/uploads/2024/02/fdm_blog_filter-1024x528.png)
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'"