Last active
September 1, 2022 04:21
-
-
Save wriglz/3cf07095e032d9c03f5829f5c7239182 to your computer and use it in GitHub Desktop.
SQL to snap points to the closest line within a predefined radius
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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
Well explained...thanks alot.