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

Availability: 1.1.0

[Warning]

This function strips the M dimension.

Examples

Merging lines with different orientation.

SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((10 160, 60 120), (120 140, 60 120), (120 140, 180 120))'
		));
--------------------------------------------
 LINESTRING(10 160,60 120,120 140,180 120)

Lines are not merged across intersections with degree > 2.

SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((10 160, 60 120), (120 140, 60 120), (120 140, 180 120), (100 180, 120 140))'
		));
--------------------------------------------
 MULTILINESTRING((10 160,60 120,120 140),(100 180,120 140),(120 140,180 120))

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

SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((-29 -27,-30 -29.7,-36 -31,-45 -33),(-45.2 -33.2,-46 -32))'
));
----------------
MULTILINESTRING((-45.2 -33.2,-46 -32),(-29 -27,-30 -29.7,-36 -31,-45 -33))

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

SELECT ST_AsText(ST_LineMerge(
'MULTILINESTRING((60 30, 10 70), (120 50, 60 30), (120 50, 180 30))',
TRUE));
-------------------------------------------------------
 MULTILINESTRING((120 50,60 30,10 70),(120 50,180 30))

Example showing Z-dimension handling.

SELECT ST_AsText(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))'
        ));
--------------------------------------------------------------------------------------------------
LINESTRING Z (-30 -29.7 5,-29 -27 11,-30 -29.7 10,-36 -31 5,-45 -33 1,-46 -32 11)

See Also

ST_Segmentize, ST_LineSubstring