Snapping points to lines is a common task when dealing with points that have to be located over lines for some specific reason.

One of the most common applications is to **locate trajectory data on a road network**. As such, it is a georeferencing problem that aims to get enhanced locations of trajectories getting rid of their deviations by using road networks as reference.

This problem, also called **point-to-curve matching**, is one of the simplest approaches for **map-matching** algorithms, which can also include topology, probability and fuzzy logic, among others. A complete review of map-matching algorithms is given by (Quddus et al., 2007).

In terms of free and open source software for Geomatics (**FOSS4G**), libraries such as Java Topology Suite (JTS) and its port to C called GEOS provide classes and functions that can be used to snap points to lines. Some examples on how to use them are provided by P. Ramsey (using SQL and PostGIS functions), Marcello Benigno (using GRASS) and GeoTools User Guide.

However, **the R package rgeos**, which is the R interface to GEOS, still doesn't provide those functions and one has to build his own ones. In the rest of this post I will show you my solution, which **snaps the trajectory points to the nearest points lying on the road network**.

First, import some road data into R (you can download the shapefile from this link, source: OpenStreetMap), don't forget to adjust the path to the data: