[postgis-users] Split a polygon to N linestrings

Kevin Neufeld kneufeld at refractions.net
Fri Jan 29 08:44:15 PST 2010


CREATE TEMP TABLE mypolygontable AS
SELECT
   'MULTIPOLYGON(((0 0, 0 4, 4 4, 4 0, 0 0),
                  (1 1, 1 2, 2 2, 2 1, 1 1)),
                 ((5 5, 5 6, 6 6, 6 5, 5 5))
                )'::geometry geom;


-- make line segments from every startpoint and endpoint
SELECT ST_AsText( ST_MakeLine(sp,ep) )
FROM
   -- extract the endpoints for every 2-point line segment for each linestring
   (SELECT
      ST_PointN(geom, generate_series(1, ST_NPoints(geom)-1)) as sp,
      ST_PointN(geom, generate_series(2, ST_NPoints(geom)  )) as ep
    FROM
       -- extract the individual linestrings
      (SELECT (ST_Dump(ST_Boundary(geom))).geom
       FROM mypolygontable
       ) AS linestrings
    ) AS segments;

       st_astext
---------------------
  LINESTRING(0 0,0 4)
  LINESTRING(0 4,4 4)
  LINESTRING(4 4,4 0)
  LINESTRING(4 0,0 0)
  LINESTRING(1 1,1 2)
  LINESTRING(1 2,2 2)
  LINESTRING(2 2,2 1)
  LINESTRING(2 1,1 1)
  LINESTRING(5 5,5 6)
  LINESTRING(5 6,6 6)
  LINESTRING(6 6,6 5)
  LINESTRING(6 5,5 5)
(12 rows)


Cheers,
Kevin

On 1/29/2010 5:16 AM, Nicolas Gillet - MARKET-IP wrote:
> Hello,
>
> I am looking for some tips to split a polygon to its simplest linestrings.
>
> An example worth better than words :
>
> POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))
>
> Would become :
>
> MULTINLINESTRING((0 0, 0 1), (0 1, 1 1), (1 1, 1 0), (1 0, 0 0))
>
> Every single linestring has to have two and only two points.
>
> Is there a way to do this with the existing postgis functions ?
>
> I found several ways to turn a polygon to a (multi)linestring but not to
> split it then into shortest linestrings.
>
> Thanks for any input.
>
> Nicolas
>
> Gillet
>
>
>
> _______________________________________________
> postgis-users mailing list
> postgis-users at postgis.refractions.net
> http://postgis.refractions.net/mailman/listinfo/postgis-users



More information about the postgis-users mailing list