Name

ST_LineMerge — Return the lines formed by sewing together a MultiLineString.

Synopsis

geometry ST_LineMerge(geometry amultilinestring);

geometry ST_LineMerge(geometry amultilinestring, boolean directed);

Description

Returns a LineString or MultiLineString formed by joining together the line elements of a MultiLineString. Lines are joined at their endpoints at 2-way intersections. Lines are not joined across intersections of 3-way or greater degree.

If directed is TRUE, then ST_LineMerge will not change point order within LineStrings, so lines with opposite directions will not be merged

[Note]

Only use with MultiLineString/LineStrings. Other geometry types return an empty GeometryCollection

Performed by the GEOS module.

Enhanced: 3.3.0 accept a directed parameter.

Requires GEOS >= 3.11.0 to use the directed parameter.

Availability: 1.1.0

[Warning]

This function strips the M dimension.

Examples

Cardinality 2

Nodes with cardinality 2 are merged away.

Code
SELECT ST_LineMerge('MULTILINESTRING((10 160,60 120),(120 140,60 120),(120 140,180 120))'
);
Output
LINESTRING(10 160,60 120,120 140,180 120)
Figure
Geometry figure for visual-st-linemerge-01

Cardinality 3 or More

Lines are not merged across intersections with degree > 2.

Code
SELECT ST_LineMerge('MULTILINESTRING((10 160,60 120),(120 140,60 120),(120 140,180 120),(100 180,120 140))'
);
Output
MULTILINESTRING((10 160,60 120,120 140),(100 180,120 140),(120 140,180 120))
Figure
Geometry figure for visual-st-linemerge-02

Non-Touching Lines

If merging is not possible due to non-touching lines, the original MultiLineString is returned.

Code
SELECT ST_LineMerge('MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45.2 -33.2,-46 -32))'
);
Output
MULTILINESTRING((-45.2 -33.2,-46 -32),(-29 -27,-30 -29.7,-36 -31,-45 -33))
Figure
Geometry figure for visual-st-linemerge-03

Directed Parameter

Lines with opposite directions are not merged if directed is TRUE.

Code
SELECT ST_LineMerge('MULTILINESTRING((60 30,10 70),(120 50,60 30),(120 50,180 30))',
TRUE);
Output
MULTILINESTRING((120 50,60 30,10 70),(120 50,180 30))
Figure
Geometry figure for visual-st-linemerge-04

Z-dimension Handling

Code
SELECT ST_LineMerge('MULTILINESTRING((-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 6),(-29 -27 12,-30 -29.7 5),(-45 -33 1,-46 -32 11))'
        );
Output
LINESTRING Z (-30 -29.7 5,-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 1,-46 -32 11)
Figure
Geometry figure for visual-st-linemerge-05