Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save maxcollombin/f687d60d444c5ae87d6d6bc7fc0ee765 to your computer and use it in GitHub Desktop.
Save maxcollombin/f687d60d444c5ae87d6d6bc7fc0ee765 to your computer and use it in GitHub Desktop.
SQL to snap points to the closest line within a predefined radius
-- Snap the points to their closest lines, found in the subquery below
SELECT
point_id,
line_id,
ST_LINE_INTERPOLATE_POINT(line_geom,
ST_Line_Locate_Point(line_geom, point_geom)) AS snapped_points --Create the snapped points
FROM
--Subquery to find the closest line to each point (within a pre-defined raidus)
(
SELECT DISTINCT ON
(pt.id) ln.geom AS line_geom,
pt.geom AS point_geom,
ln.id AS line_id,
pt.id AS point_id
FROM
point_table AS pt
INNER JOIN
line_table AS ln
ON
ST_DWithin(pt.geom,
ln.geom,
10) -- Snap points to lines within a 10m radius
ORDER BY
pt.id,
ST_Distance(ln.geom,
pt.geom)) AS closest_pnt; -- Here we order the result set by distance to find the closest line to each point, but as we have used SELECT DISTINCT, we only take the closest point.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment