9

我正在开发一个 GeoDjango 应用程序,用户可以在其中上传地图文件并执行一些基本的映射操作,例如查询多边形内的特征。

我认识到用户有时会上传“MultiLineString”而不是“Polygon”。这会导致期望封闭几何的查询失败。

在 Python 中将 MultiLineString 对象转换为多边形的最佳方法是什么?

4

3 回答 3

12

呵呵,一开始我是这样写的:

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

但后来我发现有一个漂亮的小方法,叫做convex_hull,它可以自动为你做多边形转换。

>>> 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)),)
于 2010-06-04T14:47:44.840 回答
2

这是对 Carlos 答案的修改,它更简单,不仅返回一个元素,还返回源文件中的所有行

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
于 2020-05-08T17:08:52.487 回答
2

这个小代码可以节省很多时间,也许以后在 geopandas 中会合并一个更短的形式。

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

def linestring_to_polygon(fili_shps):
    gdf = gpd.read_file(fili_shps) #LINESTRING
    geom = [x for x in gdf.geometry]
    all_coords = mapping(geom[0])['coordinates']
    lats = [x[1] for x in all_coords]
    lons = [x[0] for x in all_coords]
    polyg = Polygon(zip(lons, lats))
    return gpd.GeoDataFrame(index=[0], crs=gdf.crs, geometry=[polyg])
于 2019-07-21T19:11:29.580 回答