Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a GEOS MultiLineString to Polygon?

I am developing a GeoDjango application where users can upload map files and do some basic mapping operations like querying features inside polygons.

I recognized that users happen to upload "MultiLineString"s instead of "Polygon"s sometimes. This causes the queries expecting closed geometries to fail.

What is the best way to convert a MultiLineString object to a Polygon in Python?

like image 464
onurmatik Avatar asked Jun 03 '10 09:06

onurmatik


2 Answers

Hehe, at first I wrote this:

def close_geometry(self, geometry):
   if geometry.empty or geometry[0].empty:
       return geometry # empty

   if(geometry[-1][-1] == geometry[0][0]):
       return geometry  # already closed

   result = None
   for linestring in geom:
      if result is None:
          resultstring = linestring.clone()
      else:
          resultstring.extend(linestring.coords)

   geom = Polygon(resultstring)

   return geom

but then I discovered that there is a nifty little method called convex_hull that does the polygon conversion for you automatically.

>>> s1 = LineString((0, 0), (1, 1), (1, 2), (0, 1))
>>> s1.convex_hull
<Polygon object at ...>
>>> s1.convex_hull.coords
(((0.0, 0.0), (0.0, 1.0), (1.0, 2.0), (1.0, 1.0), (0.0, 0.0)),)

>>> m1=MultiLineString(s1)
>>> m1.convex_hull
<Polygon object at...>
>>> m1.convex_hull.coords
(((0.0, 0.0), (0.0, 1.0), (1.0, 2.0), (1.0, 1.0), (0.0, 0.0)),)
like image 117
Andriy Drozdyuk Avatar answered Oct 11 '22 22:10

Andriy Drozdyuk


Here is a modification of Carlos answer, it is simpler and returns not just one element, but all the rows in the source file

import geopandas as gpd
from shapely.geometry import Polygon, mapping

def linestring_to_polygon(fili_shps):
    gdf = gpd.read_file(fili_shps) #LINESTRING
    gdf['geometry'] = [Polygon(mapping(x)['coordinates']) for x in gdf.geometry]
    return gdf
like image 27
Nikita Pestrov Avatar answered Oct 11 '22 23:10

Nikita Pestrov