如何使用Python将GEO MultineString转换为多边形?
-
23-10-2019 - |
题
我正在开发一个Geodjango应用程序,用户可以上传地图文件并执行一些基本的映射操作,例如多边形内的查询功能。
我认识到用户有时会上传“ MultineString” S,而不是“多边形”。这导致查询期望封闭的几何形状失败。
在Python中将多轨对象转换为多边形的最佳方法是什么?
谢谢。
- omat
解决方案
呵呵,起初我写了这篇文章:
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)),)
其他提示
这个小型代码可以节省大量时间,也许以后将在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])
不隶属于 StackOverflow