使用GeoDjango将GeometryField转换为MultiPolygon?

时间:2018-06-13 15:56:46

标签: postgis gdal geodjango

我正在尝试将一堆学校边界文件添加到数据库中。边界文件不一致。它们由DataSource处理为PolygonMultiPolygonGeometryCollection

使用https://gis.stackexchange.com/questions/13498Polygon转换为MultiPolygon非常简单,但转换不适用于GeometryCollection

class School(models.Model):
    boundaries = models.MultiPolygonField()

---

from django.contrib.gis.geos import Polygon, MultiPolygon
from django.contrib.gis.geos.collections import GeometryCollection

ds = DataSource('school_boundaries.aspx')
feature = ds[0][0]
geom_geos = feature.geom.geos
if isinstance(geom_geos, Polygon):
    geom_geos = MultiPolygon(geom_geos)
elif isinstance(geom_geos, GeometryCollection):
    geom_geos = MultiPolygon(GeometryCollection)  #This does not work
school = School(boundaries = geom_geos)
school.save()

有没有办法在GeoDjango中将GeometryField转换为MultiPolygon

1 个答案:

答案 0 :(得分:1)

我找到了一个很好的解决方案。这仅在GeometryCollection是多边形数组时有效。在我的例子中,我只需要在GeometryCollection中循环多边形,将它们中的每一个附加到一个列表中,然后从多边形列表中创建一个MultiPolygon。

from django.contrib.gis.geos import MultiPolygon
from django.contrib.gis.geos.collections import GeometryCollection

ds = DataSource('school_boundaries.aspx')
feature = ds[0][0]
geom_geos = feature.geom.geos
if isinstance(geom_geos, GeometryCollection):
    poly_list = []
    for poly in geom_geos[0]:
        poly_list.append(poly)
        geom_geos = MultiPolygon(poly_list)
school = School(boundaries = geom_geos)
school.save()