8

In am a Django developer with limited GIS knowledge. In Django I have a polygon and a linestring as follows:

Linestring and Polygon

I would like to split the polygon by the linestring to obtain the 4 resulting polygons (or one new multipolygon):

New Polygons

Based on the API docs I thought I might be able to use the union method to get this, but this fails on geometry checking.

Does anyone perhaps have a suggestion on how best to achieve this?

1
  • Can you please supply example data for the polygons and the lines? (In any format, or in Python code)
    – Udi
    Commented Mar 20, 2017 at 12:44

1 Answer 1

8

You can use shapely to access the underlying GEOS API and create the polygons:

from shapely import wkt
from shapely.ops import linemerge, unary_union, polygonize

POLY = "POLYGON ((34.67491149902344 31.59900710035676, 34.85000610351562 31.59900710035676, 34.85000610351562 31.73867905688433, 34.67491149902344 31.73867905688433, 34.67491149902344 31.59900710035676))"
LINE = "LINESTRING (34.64401245117188 31.63292168314889, 34.80812072753906 31.75911546882192)"

poly = wkt.loads(POLY)
line = wkt.loads(LINE)

merged = linemerge([poly.boundary, line])
borders = unary_union(merged)
polygons = polygonize(borders)
for p in polygons:
    print(p)

Since GEOS is used by GeoDjango and shapely, data is interchangeable between them.

Solution adapted from answer here: https://stackoverflow.com/questions/4129241/split-a-polygon-with-a-linestring-in-jts

1
  • Nice answer! I think you could also follow this algorithm using PostGIS with GeoDjango. I would be interested to know if you could achieve this nicely using just GEOSGeometry operations without shapely. I had a look but I think the polygonize operation is going to be tricky.
    – Alexander
    Commented Mar 21, 2017 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.