15

I have a polygon data table in PostgreSQL/PostGIS. Now I need to convert this Polygon data into its corresponding line segments. Can anybody tell me how to convert it using PostGIS queries.

Thanks in Advance

mloskot
  • 37,086
  • 11
  • 109
  • 136
gouse shaik
  • 151
  • 1
  • 1
  • 3

2 Answers2

26

Generally, converting polygon to line may be not straightforward because there is no one-to-one mapping and various elements of polygon map to different linestring (exterior ring, interior rings, etc.).

Considering that, you will need to split each of those separately following possible approach like this:

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;

depending on what polygon data are stored in mypolygontable, you may want to dump not only the boundary (as above using ST_Boundary) but also other elements. The code above with more detailed overview is taken from the postgis-users list: Split a polygon to N linestrings

There is also a generic approach to the problem explained in Exploding a linestring or polygon into individual vectors in PostGIS

mloskot
  • 37,086
  • 11
  • 109
  • 136
-2

This is the first hit on google when you search this problem. I don't know if so much time has passed a function has been created since, but for future googlers ST_ExteriorRings(geom) worked great for me. http://postgis.net/docs/ST_ExteriorRing.html

SELECT ST_ExteriorRing(ST_Dump(geom)).geom)
FROM foo
D_C
  • 370
  • 4
  • 22
  • @DonaldDuck The answer is not 100% correct. The function name is `ST_ExteriorRing`, not `ST_ExteriorRings` (note the trailing `s`). It generates a single linestring instead of multiple line segments. It furthermore excludes the boundaries of holes. It also fails on multipolygons. – jpmc26 Jan 30 '19 at 17:42
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Donald Duck Feb 02 '19 at 21:12