| 1 | = Functions for Linear Referencing = |
| 2 | |
| 3 | These functions augment the [https://postgis.net/docs/manual-3.0/reference.html#Linear_Referencing built-in] ones in PostGIS. |
| 4 | |
| 5 | == Locate Segment Index for Point == |
| 6 | |
| 7 | This can be useful for inserting a line vertex at the location closest to a given point. |
| 8 | |
| 9 | Also see [https://postgis.net/docs/manual-3.0/ST_Snap.html ST_Snap] for doing this. |
| 10 | |
| 11 | {{{ |
| 12 | --- Locates the segment on a LineString containing the location closest to a given point. |
| 13 | --- Returns a record containing: |
| 14 | --- index: the segment index of the closest point on the line |
| 15 | --- dist: the distance to the given point |
| 16 | |
| 17 | CREATE OR REPLACE FUNCTION ST_LineLocateSegment( line geometry, pt geometry ) |
| 18 | RETURNS table(index integer, dist double precision) |
| 19 | AS $$ |
| 20 | SELECT i - 1, dist FROM ( |
| 21 | SELECT i, ST_Distance( |
| 22 | ST_MakeLine( ST_PointN( line, s.i ), ST_PointN( line, s.i+1 ) ), |
| 23 | pt) AS dist |
| 24 | FROM generate_series(1, ST_NumPoints( line )-1) AS s(i) |
| 25 | ORDER BY dist |
| 26 | ) AS t LIMIT 1; |
| 27 | $$ |
| 28 | LANGUAGE sql STABLE STRICT; |
| 29 | }}} |
| 30 | |
| 31 | Example |
| 32 | |
| 33 | {{{ |
| 34 | SELECT ST_LineLocateSegment( 'LINESTRING (0 0, 10 10, 20 20, 30 30)'::geometry, |
| 35 | 'POINT(15 15.1)'::geometry); |
| 36 | }}} |
| 37 | |