Skip to content

Instantly share code, notes, and snippets.

@i5ar
Forked from djq/unions
Last active October 17, 2016 00:09
Show Gist options
  • Save i5ar/a27a52dcc637a4918d9548fca9804871 to your computer and use it in GitHub Desktop.
Save i5ar/a27a52dcc637a4918d9548fca9804871 to your computer and use it in GitHub Desktop.
Union from a list of geometries in GeoDjango
// Encode array
var json_string = JSON.stringify(features_array);
console.log(json_string); // ["POLYGON((13.80796143 42.56851169000001,13.80769846 42.568553580000014,13.80777101 42.568770150000006,13.80804818 42.568736520000016,13.80796143 42.56851169000001))","POLYGON((13.8078327 42.56894971,13.80810299 42.568905150000006,13.80804818 42.568736520000016,13.80777101 42.568770150000006,13.8078327 42.56894971))"]
try: import simplejson as json
except ImportError: import json
from django.contrib.gis.geos import GEOSGeometry
# Decode array
polygons_string = json.loads(json_string) # [u'POLYGON((13.80796143 42.56851169000001,13.80769846 42.568553580000014,13.80777101 42.568770150000006,13.80804818 42.568736520000016,13.80796143 42.56851169000001))', u'POLYGON((13.8078327 42.56894971,13.80810299 42.568905150000006,13.80804818 42.568736520000016,13.80777101 42.568770150000006,13.8078327 42.56894971))']
# Make geometry list from unicode list
polygons_geometry = [GEOSGeometry(i) for i in polygons_string] # [<Polygon object at 0x6402eb8>, <Polygon object at 0x6402378>]
# Get first polygon
polygon = polygons_geometry[0]
# Get remaining polygons
polygons = polygons_geometry[1:]
# Union remaining polygons
for i in polygons:
polygon = polygon.union(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment