kennethj
kennethj

Reputation: 159

Problems combining (union) Multipolygons in geodjango

I'm using geodjango and postgis (1.x), What is the best way to combine (union) a list of multipolygons.

in what i assume is rather inefficient i'm looping trough like this

combined = multipolygon
for item in items:
    combined = combined.union(item.geom)  #geom is a multipolygon

Usually this works fine, but often i'm getting the error Error encountered checking Geometry returned from GEOS C function "GEOSUnion_r".

Here is the geo json version of the item the error is thrown on if it helps

{ "type": "MultiPolygon", "coordinates": 
[ [ [ [ -80.077576, 26.572225 ], 
      [ -80.037729, 26.571180 ], 
      [ -80.080279, 26.273744 ], 
      [ -80.147464, 26.310066 ], 
      [ -80.152851, 26.455851 ], 
      [ -80.138560, 26.538013 ], 
      [ -80.077576, 26.572225 ] 
] ] ] 
}

does anyone have anyideas? the end goal is to take find all the locations (another table) which fall within this list of n polygons (using coordinates__within=combined_area)

Also, the polygons show up fine on the maps in the geodjango admin.

Upvotes: 2

Views: 3527

Answers (1)

miki725
miki725

Reputation: 27861

You can always use Union aggregate method. That should be a bit more efficient because everything is computed on the database level which means you don't have to loop over things in Python.

combined_area = FooModel.objects.filter(...).aggregate(area=Union('geom'))['area']
final = BarModel.objects.filter(coordinates__within=combined_area)

Upvotes: 4

Related Questions