forked from straup/osm-tools
/
ways-to-geojson.py
executable file
·165 lines (116 loc) · 3.73 KB
/
ways-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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python
import sys
import urllib
import xml.etree.ElementTree as xml
import json
import re
import logging
import liljson
def nodes_for_way(id):
url = 'http://www.openstreetmap.org/api/0.6/way/%s' % id
logging.debug("fetch way %s" % url)
nodes = []
rsp = urllib.urlopen(url)
tree = xml.fromstring(rsp.read())
for nd in tree.findall('*//nd'):
attrs = nd.attrib
nodes.append(attrs['ref'])
return nodes
def coords_for_node(id):
url = 'http://www.openstreetmap.org/api/0.6/node/%s' % id
logging.debug("fetch node %s" % url)
rsp = urllib.urlopen(url)
tree = xml.fromstring(rsp.read())
node = tree.find('node')
attrs = node.attrib
return (
float(attrs['lon']),
float(attrs['lat'])
)
def ways_to_geojson(ids, precision=2):
features = []
for id in ids:
nodes = nodes_for_way(id)
coords = []
swlat = None
swlon = None
nelat = None
nelon = None
for n in nodes:
pt = coords_for_node(n)
coords.append(pt)
if swlat:
swlat = min(swlat, pt[1])
else:
swlat = pt[1]
if swlon:
swlon = min(swlat, pt[0])
else:
swlon = pt[0]
if nelat:
nelat = max(nelat, pt[1])
else:
nelat = pt[1]
if nelon:
nelon = max(nelon, pt[0])
else:
nelon = pt[0]
bbox = [ swlon, swlat, nelon, nelat ]
# TO DO: check to see if this a closed set of
# coordinates or not...
first = coords[0]
last = coords[-1]
if first[0] == last[0] and first[1] == last[1]:
type = 'Polygon'
coords = [ coords ]
else:
type = 'LineString'
properties = {
'id': id
}
geom = {
'type': type,
'coordinates': coords
}
feature = {
'type': 'Feature',
'bbox': bbox,
'properties': properties,
'geometry' : geom
}
features.append(feature)
geojson = {
'type': 'FeatureCollection',
'features': features
}
return geojson
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser(usage="python ways-to-geojson.py --options way-ids")
parser.add_option('--path', dest='path',
help='Where to write your GeoJSON file. Default filename is the concationation of all the way IDs, dot json.',
action='store')
parser.add_option('--precision', dest='precision',
help='The decimal precision for your GeoJSON file. Default is 6.',
action='store', default=None)
parser.add_option('--indent', dest='indent',
help='Indent your GeoJSON file. Default is false.',
action='store_true', default=False)
parser.add_option('--debug', dest='debug',
help='Enable debug logging',
action='store_true', default=False)
options, ids = parser.parse_args()
if options.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
if len(ids) == 0:
logging.error("missing way IDs")
sys.exit()
output = options.path and open(options.path, 'w') or sys.stdout
data = ways_to_geojson(ids, options.precision)
args = {}
if options.indent:
args['indent'] = options.indent
json.dump(data, output, indent=2)
logging.info("done")