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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.