Snapping a point to the nearest line

Building on our newly gained wisdom from the last recipe, we will now attack another common spatial problem. This super common spatial task is for all the GPS junkies who want their GPS coordinates to snap to an existing road. Imagine that you have some GPS tracks and you want to have these coordinates snap to your base road dataset. To accomplish such a task, we need to snap a point (GPS coordinates) to a line (roads).

The geos library is what Shapely is built on and can handle this problem with ease. We will combine the use of the shapely.interpolate and shapely.project functions to snap our point to the true nearest point on the line using linear referencing.

As you can see in the following diagram, our input ...

Get Python Geospatial Analysis Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.