[GIS] PostGIS function for determining whether a linestring intersects itself

postgis

I've been looking for a function that can tell me if a LineString intersects itself. I've tried calling st_intersects with the same LineString twice, but obviously identical linestrings will intersect. My plan if there is no function would be to get all the points in the line string, and create individual linestrings and then check each new linestring against each other one with st_intersects. I do not want it to come to this, but I'm afraid it will.

So are there any PostGIS functions for checking if a linestring is self-intersecting? It should be similar to finding out whether a polygon is complex I'd assume

Best Answer

You can test for a self-intersecting linestring with ST_IsSimple(geom):

SELECT ST_IsSimple('LINESTRING (50 50, 150 150, 50 150, 150 50)');
 st_issimple
-------------
 f
(1 row)

Self-intersection at POINT ( 100.0 100.0 )

Above image and below caption are from JTS TestBuilder (click "Simple?")

Self-intersection at POINT ( 100.0 100.0 )

This can be fixed with ST_UnaryUnion(geom) (since PostGIS 2.0), which returns a valid/simple three piece multilinestring:

MULTILINESTRING((50 50, 100 100), 
  (100 100, 150 150, 50 150, 100 100), 
  (100 100, 150 50))
Related Question