Skip to content

Instantly share code, notes, and snippets.

@sgillies
Created October 29, 2012 18:50
Show Gist options
  • Save sgillies/3975665 to your computer and use it in GitHub Desktop.
Save sgillies/3975665 to your computer and use it in GitHub Desktop.
GeoJSON demo of recursive geometry demolition.
# allasplode.py: Explode all geometries of all features in a collection into a cloud of points.
#
# GeoJSON geometry objects all have a 'coordinates' object which is multidimensional array of
# numbers. The uniformity of these objects is a good thing: it lets us go at them with recursive
# methods and helps us write less code.
#
# Input data file from http://poezn.github.com/us-history-maps/.
def explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield coordinate tuples.
As long as the input is conforming, the type of the geometry doesn't matter."""
for e in coords:
if isinstance(e, (float, int, long)):
yield coords
break
else:
for f in explode(e):
yield f
import json
data = open("1789030.json", "r").read()
collection = json.loads(data)
for feature in collection['features']:
# No matter the type of geometry, the path to every array of coordinates is the same.
points = list(explode(feature['geometry']['coordinates']))
print feature.get('id', "oh ffs"), points[0:2], len(points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment