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 Generalizing Polygons to MultiPolygons in GeoDjango?, 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)

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


A GeometryCollection can contain point and line type geometries that cannot be coerced into a MultiPolygon. You probably have three choices, the best choice depends on your needs and the data:

  1. Add MultiPoint and MultiLineString geometry fields to your model and store these separately.
  2. Polygonise the points and lines and store these in the MultiPolygon field - this is a pretty weird thing to do but if you absolutely must have only a MultiPolygon field and store everything in there, it is an option.
  3. Check to see if the points and lines are important for your purposes, if not, discard them.

You can iterate though a GeometryCollection in a way similar to this (not tested):

for geom in geometrycollection.geoms:
    # Do something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.