Is there a way to list and/or modify filters applied to a feature layer within a web map using the ArcGIS API for Python?
Can't see anything to hand in the layer class, but this post looks to be one way to do it with the JSON Solved: Filter layer inside webmap - Esri Community
Excellent, I'll give this a try.
Thanks!
I have a lot of standard layers across webmaps that require different filters for each layer of the map so I maintain a folder with a JSON file relating to each layer, this way, if a filter changes I just need to alter the JSON file and I can apply the updated filter to over 100 maps to maintain as standard. The JSON files are names the same as the layer in the webmap (well actually the same as the layer title when accessed through the Python API). The below code will apply the filters to one WebMap, I have commented the code.
An example of the JSON file filter
"(status <> 2) AND (usage = 1)"
The Python Script
# -*- coding: utf-8 -*-
from arcgis import GIS
import json
def listFilesInFolder(input_fldr, file_extension=None):
"""
Args:
input_fldr the folderpath
file_extension optional parameter to limit filetypes retured
Returns:
List of filenames in the folder
"""
if file_extension in [None, "", " "]:
return [filename for filename in os.listdir(input_fldr)]
else:
return [filename for filename in os.listdir(input_fldr) if filename.lower().endswith(file_extension)]
## path to the JSON library, where the JSON files are stored
json_fldr = r"path_to\JSON\Filters"
## the id for the webmap to update, this can be obtained from the webmap url
webmap_id = "wembap_id"
## connect to the AGOL instance
conn = GIS("home")
## reference the webamp through the id provided
item = conn.content.get(webmap_id)
## reference the webmap content/config
item_data = item.get_data()
## list json files in jsnon_fldr
json_list = listFilesInFolder(json_fldr, ".json")
## for each layer in the webmap
for index, i in enumerate(item_data["operationalLayers"]):
## get the title of the layer - how it is named as a layer service
title = item_data["operationalLayers"][index]["title"]
## you might want to print the title here to see if the title matches the name of your JSON file
## if the title has a match
if "{0}.json".format(title) in json_list:
print("\tUpdating: {0}".format(title))
## get the filters config for the layer
with open("{0}\\{1}.json".format(json_fldr, title)) as json_data:
filters = json.load(json_data)
## overwrite the current filters config
item_data["operationalLayers"][index]['layerDefinition']['definitionExpression'] = filters
## update the layer in webmap with the new filters config
item_properties = {"text":item_data}
item.update(item_properties=item_properties)
print("\t\tUpdated")
I had an epiphany looking at your post. Many thanks for sharing.
I was converging on the same approach.