PostGIS – How to Create Polygons from Gaps

polygonpostgis

Using PostGIS, I want to fill a gap between other polygons.

Image to explain from where to extract the polygon:

enter image description here

Can you help with some directions what functions to use?

Best Answer

Use ST_Union to aggregate the polygons into one polygon and then ST_InteriorRingN to get the border of the gap and ST_BuildArea to get polygon of the gap. If there is more than one such gap use generate_series and ST_NumInteriorRings. Example:

WITH polygons(geom) AS
(VALUES (ST_Buffer(ST_Point(0, 0), 1.1,3)),
        (ST_Buffer(ST_Point(0, 2), 1.1,3)),
        (ST_Buffer(ST_Point(2, 2), 1.1,3)),
        (ST_Buffer(ST_Point(2, 0), 1.1,3)),
        (ST_Buffer(ST_Point(4, 1), 1.3,3))
),
bigpoly AS
(SELECT ST_UNION(geom)geom 
 FROM polygons)
SELECT ST_BuildArea(ST_InteriorRingN(geom,i)) 
FROM bigpoly
CROSS JOIN generate_series(1,(SELECT ST_NumInteriorRings(geom) FROM bigpoly)) as i;

example Blue-start polygons Purple-final polygons

Related Question