Skip to content

Instantly share code, notes, and snippets.

@wriglz
Last active September 1, 2022 04:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wriglz/3cf07095e032d9c03f5829f5c7239182 to your computer and use it in GitHub Desktop.
Save wriglz/3cf07095e032d9c03f5829f5c7239182 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.
@bettdouglas
Copy link

Well explained...thanks alot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment