Define Area of Interest on Hosted Feature Layer View using ArcGIS API for Python
Let's say you are responsible for a Hosted Feature Layer with data for the whole country and you want to share these data with regional teams in such a way that they are able to see only records in their own region. For many practical reasons you don't want to divide your data over multiple Hosted Feature Layers. You want to create regional views on the data instead.
You can draw these regions manually, following the procedure on this page: https://doc.arcgis.com/en/arcgis-online/manage-data/set-view-definition.htm But hey, you know your regions, and you don't want to draw them by hand. Instead you want to use existing geometry and create the views automatically.
In the example below we use data from the Netherlands. We have a data set with police stations ('Politiebureaus') and one with provinces ('Provincies (Bestuurlijke Grenzen 2019)') - with the ArcGIS Online Assistant we have copied these data sets to our own environment.
See the script below how we create twelve views - one for each province - showing only the police stations within the provincial boundaries
Hope this helps!
P.S. for another example - setting a view definition - you might have a look at this blog https://community.esri.com/groups/arcgis-python-api/blog/2019/02/11/using-the-arcgis-api-for-python-... by Earl Medina.
from arcgis.gis import GIS
from arcgis.features import FeatureLayerCollection
from provide_credentials import provide_credentials
username, password = provide_credentials()
my_agol = GIS("https://www.arcgis.com", username, password)
police_stations = my_agol.content.get('<itemID>')
police_stations_flc = FeatureLayerCollection.fromitem(police_stations)
provinces = my_agol.content.get('<itemID>').layers[0].query()
spat_ref = provinces.spatial_reference
for index, province in enumerate(provinces):
prov_name = provinces.features[index].attributes['Provincienaam'].upper().replace('-','_')
print(prov_name)
view_name = police_stations.name + "_" + prov_name + "_View"
print(view_name)
view_geom = provinces.features[index].geometry.get('rings')
new_view = police_stations_flc.manager.create_view(name=view_name)
view_search = my_agol.content.search(view_name)[0]
view_flc = FeatureLayerCollection.fromitem(view_search)
service_layer = view_flc.layers[0]
update_dict = {"viewLayerDefinition":{"filter":
{"operator":"esriSpatialRelContains","value":
{"geometryType":"esriGeometryPolygon","geometry":
{"rings": view_geom,
"spatialReference":spat_ref}}}}}
service_layer.manager.update_definition(update_dict)
print('Done!')