Spatial analysis often involves answering a deceptively simple question: How many features are located within each area? How many properties are in each district? How many trees are in each park? How many incidents occurred in each administrative boundary? How many inspection points fall within each service area?
This post walks through a Python script that counts points within polygons and writes the resulting totals back to the polygon layer.
Import the required classes and functions
from arcgis.gis import GIS
from arcgis.features import FeatureLayer
from arcgis.geometry.filters import intersects
The GIS class is used to connect to ArcGIS Online or an ArcGIS Enterprise portal. It provides access to portal content, users, groups, maps, layers, and other GIS resources.
The FeatureLayer class represents a feature layer and provides methods for querying and editing its data. In this workflow, it is used to access both the point and polygon layers.
The intersects geometry filter creates a spatial query based on whether features intersect a supplied geometry. This is the key spatial component of the workflow. It allows the script to ask: which points intersect this polygon?
User inputs
point_fl_url = "FL_URL"
polygon_fl_url = "FL_URL"
count_field = "FIELD_NAME"
Replace FL_URL with the URL to your point and polygon feature layers. Update the FIELD_NAME with the name of the field in the polygon feature layer that the points count will be calculated for.
Connect to ArcGIS Online (or Portal)
agol = GIS("home")
This connects to the active ArcGIS Online session using the "home" authentication profile.
Create the FeatureLayer objects
## get the Point feature layer as a FeatureLayer object
pt_fl = FeatureLayer(
url = point_fl_url,
gis = agol
)
## get the Polygon feature layer as a FeatureLayer object
ply_fl = FeatureLayer(
url = polygon_fl_url,
gis = agol
)
This creates a FeatureLayer object for the point and polygon layers.
Get a FeatureSet object representing all polygon features
## get a FeatureSet object of all polygons
ply_fset = ply_fl.query(
out_fields = [count_field]
)
A FeatureSet contains a collection of features returned by the query. Each feature contains attributes and geometry. Here, the fields returned have been limited to the count_field only. The OID field is also returned.
You need to process each polygon individually. You have all the polygon features that can be used to get each polygon's geometry as the spatial filter for the point query.
Count points in each polygon
## for each polygon feature
for feature in ply_fset.features:
## create a spatial relationship geometry dictionary using intersects
geom_filter = intersects(geometry=feature.geometry)
## count the intersecting points
pt_count = pt_fl.query(
geometry_filter = geom_filter,
return_count_only=True
)
## update the attribute in the polygon feature set
feature.attributes[count_field] = pt_count
For each polygon, you create a geometry filter using the intersects() function and the geometry of the polygon.
The FeatureLayer.query() method has a return_count_only parameter, when used with the geometry_filter parameter, will return the count of the points that intersect the polygon geometry.
You update the attributes for the user supplied count_field in the polygon feature set. This updated feature set can be used to update values in the original polygon feature service.
Apply the updates to the polygon layer
At this point, the value has not yet been written back to the polygon feature layer. The script has buit an updated collection of polygon features in memory, held in the feature set.
## update the polygon feature layer with the point counts
ply_fl.edit_features(
updates = ply_fset
)
The FeatureLayer.edit_features() method is used to apply edits to a feature layer. The updates parameter specifies the features whose attributes should be updated. In this case, you are passing in an updated FeatureSet
Behind the scenes, the OID field is being used to match the features from the feature set to the features in the feature layer and perform the update.
Check out the video above for more information and a walkthrough with an ArcGIS Online Notebook detailing outputs at fifferent tages of the script.
Idea Support
This workflow would be made significantly more efficient if the FeatureLayer.calculate() method accepted an Arcade expression. For example, look how easy it is with ArcPy:
arcpy.management.CalculateField(
in_table = polygon_features,
field = count_field,
expression = f"""var points = Filter(FeatureSetByName($datastore, "{point_features}", ["{where_clause.split(" ")[0]}"], false), "{where_clause}")
return Count(Intersects(points, $feature))""",
expression_type = "ARCADE"
)
Please support this idea to enable Arcade expressions for calculating persistent values with the ArcGIS API for Python.
Completed Script
from arcgis.gis import GIS
from arcgis.features import FeatureLayer
from arcgis.geometry.filters import intersects
########################################################################################
## USER INPUTS #########################################################################
point_fl_url = "FL_URL"
polygon_fl_url = "FL_URL"
count_field = "FIELD_NAME"
########################################################################################
## ACCESS AGOL #########################################################################
agol = GIS("home")
########################################################################################
## GET FEATURELAYER OBJECTS ############################################################
## get the Point feature layer as a FeatureLayer object
pt_fl = FeatureLayer(
url = point_fl_url,
gis = agol
)
## get the Polygon feature layer as a FeatureLayer object
ply_fl = FeatureLayer(
url = polygon_fl_url,
gis = agol
)
########################################################################################
## WORKFLOW ############################################################################
## get a FeatureSet object of all polygons
ply_fset = ply_fl.query(
out_fields = [count_field]
)
## for each polygon feature
for feature in ply_fset.features:
## create a spatial relationship geometry dictionary using intersects
geom_filter = intersects(geometry=feature.geometry)
## count the intersecting points
pt_count = pt_fl.query(
geometry_filter = geom_filter,
return_count_only=True
)
## update the attribute in the polygon feature set
feature.attributes[count_field] = pt_count
## update the polygon feature layer with the point counts
ply_fl.edit_features(
updates = ply_fset
)
########################################################################################
print("\nSCRIPT COMPLETE")