I would like to make a spatial join and use every join feature only once.
Current Input
Wish
Spatial join should match every accident to one and only one road. Output should have a Join count with the number of accidents that happened on each road segment. Each accident should therefore be counted on the closest road segment.
Problem
The only thing that doesn't work until now is, that the accidents can be assigned to multiple road segments this way. How can I prevent this?
Are you using
Add Spatial Join (Data Management)—ArcGIS Pro | Documentation
which supports one-to-one
or
Spatial Join (Analysis)—ArcGIS Pro | Documentation
which supports one-to-many
I'm using the latter, Spatial Join (Analysis)
You can create a script tool for this.
You can rename the variable names if you like, in my case I was joining crashes to roads.
Here are the parameters:
And here is the execution code:
import arcpy
import os
# Define inputs and outputs
crash_points = arcpy.GetParameterAsText(0) # Input crash points
road_lines = arcpy.GetParameterAsText(1) # Input road lines
output_feature_class = arcpy.GetParameterAsText(2) # Output feature class
search_radius = arcpy.GetParameterAsText(3) # Search radius (e.g., "500 Meters")
near_table = os.path.join("in_memory", "near_table") # Temporary Near Table
try:
# Step 1: Generate Near Table
arcpy.AddMessage("Generating Near Table...")
arcpy.GenerateNearTable_analysis(
in_features=crash_points,
near_features=road_lines,
out_table=near_table,
search_radius=search_radius,
location="NO_LOCATION",
angle="NO_ANGLE",
closest="CLOSEST" # Only find the single closest feature
)
# Step 2: Summarize crashes per road
arcpy.AddMessage("Summarizing crashes per road...")
summary_table = os.path.join("in_memory", "summary_table")
arcpy.Statistics_analysis(
in_table=near_table,
out_table=summary_table,
statistics_fields=[["IN_FID", "COUNT"]],
case_field="NEAR_FID"
)
# Step 3: Add crash counts (Join_Count) to roads
arcpy.AddMessage("Joining crash counts to roads...")
arcpy.MakeFeatureLayer_management(road_lines, "road_lines_lyr")
arcpy.AddJoin_management(
in_layer_or_view="road_lines_lyr",
in_field="OBJECTID",
join_table=summary_table,
join_field="NEAR_FID"
)
# Export joined features with crash counts
arcpy.CopyFeatures_management("road_lines_lyr", output_feature_class)
arcpy.AddMessage(f"Spatial join completed. Output saved to {output_feature_class}")
except Exception as e:
arcpy.AddError(f"An error occurred: {e}")
raise
In my case, I only needed the join count per target feature. You may need to edit it if you need more information.