I’ve recently starting scripting ArcGIS using Python as part of one of my academic projects (about which I’ll post more later) and needed to be able to snap points to polylines – that is, move points so that they lie on the nearest polyline. An example would help to explain this:
In the image above, the black line is the relevant polyline, and the blue point is the original point. I wanted this point to lie on the line itself, which it did after processing (the red point).
A number of forum posts I read on the internet about this directed me to Hawth’s Tools for ArcGIS, but sadly these don’t work with ArcGIS 9.3, which is the version I am using. Instead, I wrote the Python code below which does the job using the ArcGIS Near (Analysis) command. The Python code is shown below, and is well commented so that it should be relatively easy to understand.
# ------ Snap Point to Line ------ # Author: Robin Wilson ([email protected]) # Description: Move the points in points so that they # lie on top of the nearest line # -------------------------------- def snap_point_to_line(points, lines): # Load the Analysis toolbox so that the Near tool is available gp.toolbox = "analysis" # Perform the Near operation looking for the nearest line # (from the lines Feature Class) to each point (from the # points Feature Class). The third argument is the search # radius - blank means to search as far as is needed. The # fourth argument instructs the command to output the # X and Y co-ordinates of the nearest point found to the # NEAR_X and NEAR_Y fields of the points Feature Class gp.near(points, lines, "", "LOCATION" # Create an update cursor for the points Feature Class # making sure that the NEAR_X and NEAR_Y fields are included # in the return data rows = gp.UpdateCursor(points, "", "", "NEAR_X, NEAR_Y") row = rows.Next() # For each row while row: # Get the location of the nearest point on one of the lines # (added to the file as fields by the Near operation above new_x = row.GetValue("NEAR_X") new_y = row.GetValue("NEAR_Y") # Create a new point object with the new x and y values point = gp.CreateObject("Point") point.x = new_x point.y = new_y # Assign it to the shape field row.shape = point # Update the row data and move to the next row rows.UpdateRow(row) row = rows.Next()
This script is included in RTWTools for ArcGIS, where it is integrated into an ArcGIS Toolbox.