This repository has been archived by the owner on Mar 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
csv_to_geojson.py
92 lines (67 loc) · 2.28 KB
/
csv_to_geojson.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/usr/bin/python2.7
# Python program for changing the consentagreements.csv into useable geojson
with open('consentagreements.csv', 'r') as csv_file:
text = csv_file.read().strip().split('\n')
header_row = text[0].split(',')
dictionary = {}
for row, line in enumerate(text[1:]):
dictionary[row] = {}
for col, cell in enumerate(line.split(',')):
dictionary[row][header_row[col]] = cell
geojson = []
for row in dictionary.keys():
geojson.append(' {')
geometry = ['0','0']
properties = []
address = ['','','']
for column, cell in dictionary[row].items():
if cell.strip() == '':
cell = '" "'
if column == '"Latitude"':
geometry[1] = '\t {0}'.format(cell)
elif column == '"Longitude"':
geometry[0] = '\t {0}'.format(cell)
elif column == '"City"':
address[0] = cell
elif column == '"State"':
address[1] = cell
elif column == '"Zip"':
address[2] = cell
elif column == '"Title"':
properties.append(' "name": {0},'.format(cell))
else:
properties.append(' {0}: {1},'.format(column, cell))
geojson.append(' "type": "Feature",')
geojson.append(' "geometry": {')
geojson.append(' "type": "Point",')
geojson.append(' "coordinates": [')
geojson.append(',\n'.join(geometry))
geojson.append(' \t]')
geojson.append(' },')
geojson.append(' "properties": {')
geojson.append(' "marker-symbol": "marker",')
geojson.append(' "marker-color": "#D4500F",')
geojson.append(' "address": "{0}",'.format(' '.join(address).replace('"','')))
# Remove trailing comma from last item in properties
last = properties.pop()
properties.append(last[:-1])
geojson.extend(properties)
geojson.append(' }')
geojson.append(' },\n')
# Remove trailing commas from last item in geojson
geojson.pop()
geojson.append(' }\n')
# Create prefix and suffix to wrap around all features to make it .geojson
prefix = '''
{
"type": "FeatureCollection",
"features": [
'''
suffix = '''
]
}
'''
geojson.insert(0, prefix)
geojson.append(suffix)
with open('consentagreements.json', 'w') as geojson_file:
geojson_file.write('\n'.join(geojson))