Google Maps API Tutorial

Snap point to street

It is now possible (in countries that support directions) to snap points to the nearest street that's in the Google database.

This could be useful if you want to record a specific path by drawing a polyline that follows the streets.

The effect is achieved by requesting directions from the clicked point to itself.
When the directions information returns, it will include a polyline with a single vertex.
This polyline "follows" the street grid, and that vertex is the nearest point that lies on the street grid.
So instead of plotting the point exactly where the user clicked, we can plot the point at the returned street vertex.

Here's a simple example. Click on the map and the marker will be added to the nearest known street.

In this example, the markers are draggable and snap to a street when the drag ends.

In this example, polylines following the streets are added between the snapped points.

In this example, the two previous features are combined. Polylines are redrawn when a marker is dragged.

Potential Pitfalls

Some of the very small streets shown on the map are not in the street garid database.
E.g. the small streets to the East of the A583 roundabout in the first example are paths inside a caravan park,
points will not snap to those paths because they're not in the street database.

Don't try to snap all the points in your database dynamically,
there are issues with running multiple GDirections calls at the same time.
Snap your points, one by one, offline and store the snapped locations in your database.