I'm using GeoDjango (but I guess this is from the geos library). I have a set of polygons that compose a city surface and I want to merge them into a single one.

The code looks like this:

polygons = [zone.poly for zone in self.zone_set.all()]
poly = polygons[0]
for pol in polygons[1:]:
    poly = poly.union(pol)
self.poly = poly

The problem with this is I get a TopologyException after the first three mergings, stating there is a self-intersection

Shouldn't overlapping points be merged as a 'union'?


If I understood your question right, what you are trying to do is an aggregate union of a Django GeoQuerySet. There are functions for this that are easier to use and probably more efficient than the loop from you question.

You have two options: there is the collect command, which creates one multipolygon collection without dissolving the boundaries, and the unionagg function which computes a properly dissolved multipolygon from the queryset.

So if you need the "dissolved" union, you could try something like this:

qs = self.zone_set.all()
self.poly = qs.unionagg()

The self-intersection error you get is probably due to an invalid geometry. The recursive union in you loop might return invalid geometries and crash on the next step. You could check for that using the valid and valid_reason properties of your geometries.


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.