[postgis-users] why doesn't linemerge() work?

Andrew Ukrainec aukrainec at accipiterradar.com
Thu Oct 18 15:27:26 PDT 2012


I've been trying to append a new LINESTRING to an existing
LINESTRING in a table, and this seems to be an impossible
task.  I've searched the net for solutions, and tried all
possible obvious approaches:

ST_LineMerge(ST_Collect(geom1,geom2))
ST_LineMerge(ST_Union(geom1,geom2))
...

I wrote a function to use the aggregate version of the call

ST_LineMerge(ST_Collect(geom))

I keep getting a MULTILINESTRING() at the output rather
than a single LINESTRING().

If I run this example adapted from an example on
the OSGeo site:

SELECT ST_AsText(ST_LineMerge(ST_Collect(the_geom)))
   FROM (SELECT 'LINESTRING(0 0, 0 1)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(1 0, 1 1)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(0 0, 1 0)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(1 1, 0 1)'::geometry the_geom) as a;

I get a single LINESTRING that I hoped for,

   LINESTRING(0 0, 1 0, 1 1, 0 1, 0 0)

but the answer is completely counter intuitive to me.
I expected the individual LINESTRINGs to be simply appended
in order.  If I adjust the data in the first LINESTRING so
that '0 1' point is now '1 0':

SELECT ST_AsText(ST_LineMerge(ST_Collect(the_geom)))
   FROM (SELECT 'LINESTRING(0 0, 1 0)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(1 0, 1 1)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(0 0,1 0)'::geometry the_geom
   UNION ALL
   SELECT 'LINESTRING(1 1, 0 1)'::geometry the_geom) as a;

then again the operation fails and I get MULTILINESTRING()
at the output.

   MULTILINESTRING((1 0,1 1,0 1),(1 0,0 0,1 0))

The PostGIS documentation only contains the mysterious
statement in the Example section:

"--If can't be merged - original MULTILINESTRING is returned"

I can accept that LINEMERGE() does not work the way I imagined
it would, but then there is no explanation of how it does work
in the documentation.  In the case that one wants to glue
two LINESTRING() together into a single LINESTRING() preserving
the order of the points, can anyone suggest how this can
be done efficiently?

Thanks in advance.




More information about the postgis-users mailing list