ST_ShortestLine — Returns the 2D shortest line between two geometries
geometry ST_ShortestLine(geometry
geom1, geometry
geom2);
geography ST_ShortestLine(geography
geom1, geography
geom2, boolean use_spheroid = true);
Returns the 2-dimensional shortest line between two geometries.
The line returned starts in geom1 and ends in geom2.
If geom1 and geom2 intersect
the result is a line with start and end at an intersection point.
The length of the line is the same as ST_Distance returns for g1 and g2.
Enhanced: 3.4.0 - support for geography.
Availability: 1.5.0
Shortest line between a Point and a LineString.
SELECT ST_ShortestLine(
'POINT (160 40)',
'LINESTRING (10 30,50 50,30 110,70 90,180 140,130 190)') As sline;
LINESTRING(160 40,125.75342465753425 115.34246575342466)
Shortest line between polygons.
SELECT ST_ShortestLine(
'POLYGON ((190 150,20 10,160 70,190 150))',
ST_Buffer('POINT(80 160)', 30)
) AS llinewkt;
LINESTRING(131.59149149528952 101.89887534906195,101.21320343559643 138.78679656440357)
To connect each site to its nearest road, first select one road per site, then construct the connection. For an indexed nearest-neighbor join on table data, see <->.
WITH sites(id, geom) AS (VALUES (1, 'POINT(0 0)'::geometry)),
roads(id, geom) AS (
VALUES (1, 'LINESTRING(2 -1,2 1)'::geometry),
(2, 'LINESTRING(4 -1,4 1)')
)
SELECT sites.id AS site_id, nearest.id AS road_id,
ST_ShortestLine(sites.geom, nearest.geom) AS connection
FROM sites
CROSS JOIN LATERAL (
SELECT id, geom FROM roads
ORDER BY geom <-> sites.geom, id
LIMIT 1
) AS nearest;
site_id | road_id | connection
---------+---------+---------------------
1 | 1 | LINESTRING(0 0,2 0)
(1 row)
ST_ClosestPoint, ST_Distance, ST_LongestLine, ST_MaxDistance