/
geojs.py
78 lines (55 loc) · 2.27 KB
/
geojs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
import json
from collections import OrderedDict
from io import StringIO
import agate
def geojson2csv(f, key=None, **kwargs):
"""
Convert a GeoJSON document into CSV format.
"""
js = json.load(f, object_pairs_hook=OrderedDict)
if not isinstance(js, dict):
raise TypeError('JSON document is not valid GeoJSON: Root element is not an object.')
if 'type' not in js:
raise TypeError('JSON document is not valid GeoJSON: No top-level "type" key.')
if js['type'] != 'FeatureCollection':
raise TypeError('Only GeoJSON with root FeatureCollection type is supported. Not %s' % js['type'])
if 'features' not in js:
raise TypeError('JSON document is not a valid FeatureCollection: No top-level "features" key.')
features = js['features']
features_parsed = [] # tuples in the format (id, properties, geometry)
property_fields = []
for feature in features:
properties = feature.get('properties', {})
for prop in properties.keys():
if prop not in property_fields:
property_fields.append(prop)
geometry = feature['geometry']
if geometry:
geometry_type = geometry.get('type')
else:
geometry_type = None
if geometry_type == 'Point' and 'coordinates' in geometry:
longitude, latitude = geometry['coordinates'][0:2] # Drop altitude or elevation.
else:
longitude, latitude = (None, None)
features_parsed.append((feature.get('id'), properties, json.dumps(
geometry), geometry_type, longitude, latitude))
header = ['id']
header.extend(property_fields)
header.extend(('geojson', 'type', 'longitude', 'latitude'))
o = StringIO()
writer = agate.csv.writer(o)
writer.writerow(header)
for geoid, properties, geometry, geometry_type, longitude, latitude in features_parsed:
row = [geoid]
for field in property_fields:
value = properties.get(field)
if isinstance(value, OrderedDict):
value = json.dumps(value)
row.append(value)
row.extend((geometry, geometry_type, longitude, latitude))
writer.writerow(row)
output = o.getvalue()
o.close()
return output