Monday 3 February 2020

python - Splitting Polygon by Linestring in GeoDjango?


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?



Answer



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


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...