How to do it...

We expect this function to take a geometry and return a multi-polygon geometry:

CREATE OR REPLACE FUNCTION chp04.polygonize_to_multi (geometry) RETURNS geometry AS $$ 

For readability, we will use a WITH statement to construct the series of transformations in geometry. First, we will polygonize:

WITH polygonized AS ( 
  SELECT ST_Polygonize($1) AS the_geom 
), 

Then, we will dump:

dumped AS ( 
  SELECT (ST_Dump(the_geom)).geom AS the_geom FROM polygonized 
) 

Now, we can collect and construct a multi-polygon from our result:

SELECT ST_Multi(ST_Collect(the_geom)) FROM dumped; 

Put this together into a single function:

CREATE OR REPLACE FUNCTION chp04.polygonize_to_multi (geometry) RETURNS geometry AS $$ WITH polygonized AS ( SELECT ...

Get PostGIS Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.