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 point is located on the sun icon. The green line is what we want to snap our point to at the nearest location. The gray icon with a point on it is our result that represents the nearest point on the line from our original x position.