Jack
Jack

Reputation: 437

Converting GeometryField to MultiPolygon using GeoDjango?

I am trying to add a bunch of school boundary files into the database. The boundary files are inconsistent. They are processed by DataSource as either Polygon, MultiPolygon, or GeometryCollection.

Converting Polygon into MultiPolygon is fairly simple using https://gis.stackexchange.com/questions/13498, but the conversion does not work for 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()

Is there some way to convert GeometryField to MultiPolygon in GeoDjango?

Upvotes: 1

Views: 1415

Answers (1)

Jack
Jack

Reputation: 437

I figured out a good solution. This only works if the GeometryCollection is an array of Polygons. In my case I just had to loop over the Polygons in the GeometryCollection, append each of them to a list, and create a MultiPolygon from the list of Polygons.

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()

Upvotes: 1

Related Questions