[GIS] PostGIS – Intersects feature to split into linestring

intersectionlinestringpostgispostgresql

I would like to know if it's possible to intersect feature datasets (multipolygon, polygon, multilinestring and linestring) to get a result as a set of linestrings being split at each intersection point.

enter image description here

Output should give:

  • 4 linestrings for the square
  • 3 linestrings for the line
  • 2 linestrings for the polygon

Best Answer

First, for polygons, you want the outer boundary of the polygon as a line using ST_Boundary. Then you want a combination of ST_Intersection and ST_SymDifference

So something like (untested):

WITH firststep AS( SELECT id, ST_BOUNDARY(geom) AS boundary
FROM polygons)

SELECT p.id, ST_Intersection(boundary, geom), o.id
FROM firststep p
INNER JOIN othergeoms o ON ST_INTERSECTS(boundary, geom)

UNION

SELECT p.id, ST_SymDifference(boundary, geom), o.id
FROM firststep p
INNER JOIN othergeoms o ON ST_INTERSECTS(boundary, geom)