我正在尝试将一堆学校边界文件添加到数据库中。边界文件不一致。它们由DataSource
处理为Polygon
,MultiPolygon
或GeometryCollection
。
使用https://gis.stackexchange.com/questions/13498将Polygon
转换为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
?
答案 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()