Select to view content in your preferred language

Search by location analog with ArcGIS Python API

222
1
01-19-2024 10:44 AM
Labels (1)
Have_You_Seen_My_Rabbit
New Contributor

Hello everyone, 

The following script uses Search by Location on a polygon feature class to select points within a given threshold. The selected points then record the name of the polygon feature in a field called "Assoc_Polygon". 

def update_points_association(point_fc, polygon_fc, distance_threshold, field_name):
    # Iterate through each polygon feature
    with arcpy.da.SearchCursor(polygon_fc, ["Name", "SHAPE@"]) as polygon_cursor:
        for polygon_row in polygon_cursor:
            polygon_name = polygon_row[0]
            polygon_geometry = polygon_row[1]

            # Use SelectLayerByLocation to select points within the specified distance of the current polygon feature
            arcpy.SelectLayerByLocation_management(point_fc, "WITHIN_A_DISTANCE", polygon_geometry, distance_threshold)

            # Update the specified field in the selected points with the current polygon name
            with arcpy.da.UpdateCursor(point_fc, ["SHAPE@", field_name]) as point_cursor:
                for point_row in point_cursor:
                    point_row[1] = polygon_name
                    point_cursor.updateRow(point_row)

            # Remove the selection
            arcpy.SelectLayerByAttribute_management(point_fc, "CLEAR_SELECTION")

 

I know I can buffer polygons and then spatial join, but that seems cumbersome and uses credits. Is there any other way? Thanks!

0 Kudos
1 Reply
Clubdebambos
Occasional Contributor III

Hi @Have_You_Seen_My_Rabbit 

You are using ArcPy in this example and not the ArcGIS API for Python, as such there is no credit consumption as ArcGIS Pro (or ArcMap) is performing the geoprocessing and not ArcGIS Online.

~ learn.finaldraftmapping.com