ST_SharedPaths
Returns a geometry collection of paths shared by two lineal geometry objects. Use ST_SharedPaths to detect overlapping segments between line geometries, such as shared road segments in a road network.
Syntax
geometry ST_SharedPaths(geometry lineal1, geometry lineal2)Parameters
| Parameter | Description |
|---|---|
lineal1 | The first lineal geometry (LINESTRING or MULTILINESTRING). The direction of this geometry determines how shared paths are classified in the result. |
lineal2 | The second lineal geometry (LINESTRING or MULTILINESTRING). |
Return value
A GeometryCollection with two elements:
First element: Paths that run in the same direction as
lineal1.Second element: Paths that run in the opposite direction to
lineal1.
Both elements are returned as MULTILINESTRING. If no paths fall into a category, the corresponding element is MULTILINESTRING EMPTY.
Examples
Same-direction shared paths
The two line geometries share the segment (0 0,0 1) and travel in the same direction, so the shared path appears in the first element of the result.
SELECT
ST_AsText(ST_GeometryN(g, 1)) AS same_direction,
ST_AsText(ST_GeometryN(g, 2)) AS opposite_direction
FROM (
SELECT ST_SharedPaths(
'LINESTRING(-1 0,0 0,0 1)'::geometry,
'LINESTRING(0 0,0 1,1 1)'::geometry
) AS g
) AS t;Result:
same_direction | opposite_direction
-------------------------+-----------------------
MULTILINESTRING((0 0,0 1)) | MULTILINESTRING EMPTY
(1 row)Opposite-direction shared paths
Reversing the direction of lineal1 causes the same shared segment to appear in the second element instead.
SELECT
ST_AsText(ST_GeometryN(g, 1)) AS same_direction,
ST_AsText(ST_GeometryN(g, 2)) AS opposite_direction
FROM (
SELECT ST_SharedPaths(
'LINESTRING(0 1,0 0,-1 0)'::geometry,
'LINESTRING(0 0,0 1,1 1)'::geometry
) AS g
) AS t;Result:
same_direction | opposite_direction
-----------------+---------------------------
MULTILINESTRING EMPTY | MULTILINESTRING((0 1,0 0))
(1 row)What's next
To process the returned GeometryCollection, use these functions:
ST_GeometryN(g, n)— Extract the nth element (1 for same-direction, 2 for opposite-direction paths).