-
Notifications
You must be signed in to change notification settings - Fork 31
/
map_server.py
454 lines (348 loc) · 14.4 KB
/
map_server.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
import pymongo
from pymongo import Connection
from xml.sax.saxutils import escape
import re
class OsmApi:
def __init__(self):
self.client = Connection()
def getNodesQuery(self, query):
cursor = self.client.osm.nodes.find(query)
nodes = {}
for row in cursor:
nodes[row['_id']] = row
return nodes
def getNodes(self, query):
nodes = self.getNodesQuery(query)
return {'nodes': nodes.values()}
def getWaysInBounds(self, box):
return self.getWaysQuery([('bbox', box)])
def getWaysQuery(self, query):
cursor = self.client.osm.ways.find(query)
ways = {}
for row in cursor:
ways[row['_id']] = row
return ways
def getWays(self, query):
ways = self.getWaysQuery(query)
nodes = {}
nodes = self.getNodesFromWays(ways, nodes)
return {'nodes': nodes.values(), 'ways': ways.values()}
def getNodesFromWays(self, ways, existingNodes):
nodeIds = set()
for way in ways.values():
for nodeId in way['nd']:
nodeIds.add(nodeId)
cursor = self.client.osm.nodes.find({'_id': {'$in': list(nodeIds)} })
for row in cursor:
if row['_id'] not in existingNodes:
existingNodes[row['_id']] = row
return existingNodes
def getWaysFromNodes(self, nodes):
wayIds = set()
for node in nodes:
wayIdsFromNode = self.getWayIdsUsingNodeId(node['_id'])
for wayId in wayIdsFromNode:
wayIds.add(wayId)
ways = []
for wayId in wayIds:
way = self.client.osm.ways.find_one({'_id' : wayId})
if way:
ways.append(way)
else:
print "Error. Couldn't find way id %d." % wayId
return ways
def getWayIdsUsingNodeId(self, id):
cursor = self.client.osm.nodes.find_one({'_id' : id }, ['ways'])
if cursor and 'ways' in cursor:
return cursor['ways']
else:
return []
def getRelationsFromWays(self, ways):
relationIds = set()
for (wid, way) in ways.items():
id = way['_id']
relationIdsFromWay = self.getRelationIdsUsingWayId(id)
for relationId in relationIdsFromWay:
relationIds.add(relationId)
relations = []
for relationId in relationIds:
relation = self.client.osm.relations.find_one({'_id' : relationId})
if relation:
relations.append(relation)
else:
print "Error. Couldn't find relation id %d." % relationId
return relations
def getRelationIdsUsingWayId(self, id):
cursor = self.client.osm.ways.find_one({'_id' : id }, ['relations'])
if cursor and 'relations' in cursor:
return cursor['relations']
else:
return []
def getNodeById(self, id):
cursor = self.client.osm.nodes.find_one({'_id' : id })
if cursor:
return {'nodes': [cursor]}
else:
return {}
def getWayById(self, id):
print id
cursor = self.client.osm.ways.find_one({'_id' : id })
if cursor:
return {'ways': [cursor]}
else:
return {}
def getRelationById(self, id):
cursor = self.client.osm.relations.ways.find_one({'_id' : id })
if cursor:
return {'relations': [cursor]}
else:
return {}
def getPrimitives(self, xapi_query):
nodes = self.getNodesQuery(xapi_query)
ways = self.getWaysQuery(xapi_query)
nodes = self.getNodesFromWays(ways, nodes)
return {'nodes': nodes.values(), 'ways': ways.values()}
def getBbox(self, bbox):
import time, sys
start = time.time()
nodes = self.getNodesQuery(bbox)
timeA = time.time()
sys.stderr.write("<!-- Get nodes in bbox %s -->\n" % (timeA - start))
ways = self.getWaysQuery(bbox)
timeB = time.time()
sys.stderr.write("<!-- Get ways in bbox %s -->\n" % (timeB - timeA))
wayNodes = self.getNodesFromWays(ways, nodes)
timeC = time.time()
sys.stderr.write("<!-- Get nodes from ways %s -->\n" % (timeC - timeB))
timeD = time.time()
sys.stderr.write("<!-- Collate nodes from ways %s -->\n" % (timeD - timeC))
relations = self.getRelationsFromWays(ways)
timeE = time.time()
sys.stderr.write("<!-- Get relations %s -->\n" % (timeE - timeD))
bboxArr = bbox['loc']['$within']['$polygon']
doc = {'bounds': {'minlat': bboxArr[0][0],
'minlon': bboxArr[0][1],
'maxlat': bboxArr[2][0],
'maxlon': bboxArr[2][1]},
'nodes': nodes.values(),
'ways': ways.values(),
'relations': relations}
return doc
class OsmXmlOutput:
def addNotNullAttr(self, mappable, mappableElement, name, outName=None):
if not outName:
outName = name
if name in mappable:
mappableElement.setAttribute(escape(outName), escape(unicode(mappable[name])))
def defaultAttrs(self, mappableElement, mappable):
self.addNotNullAttr(mappable, mappableElement, "_id", "id")
self.addNotNullAttr(mappable, mappableElement, "v", "version")
self.addNotNullAttr(mappable, mappableElement, "un", "user")
self.addNotNullAttr(mappable, mappableElement, "ts", "timestamp")
def tagNodes(self, doc, mappableElement, mappable):
if 'tg' in mappable:
for mappable in mappable['tg']:
tagElement = doc.createElement("tag")
k,v = mappable
tagElement.setAttribute("k", k)
tagElement.setAttribute("v", v)
mappableElement.appendChild(tagElement)
def iter(self, data):
from xml.dom.minidom import Document
doc = Document()
yield '<osm generator="%s" version="%s">\n' % ("mongosm 0.1", "0.6")
if 'bounds' in data:
yield '<bounds minlat="%s" minlon="%s" maxlat="%s" maxlon="%s"/>\n' % (
str(data['bounds']['minlat']),
str(data['bounds']['minlon']),
str(data['bounds']['maxlat']),
str(data['bounds']['maxlon']))
if 'nodes' in data:
for node in data['nodes']:
nodeElem = doc.createElement("node")
nodeElem.setAttribute("lat", str(node['loc'][0]))
nodeElem.setAttribute("lon", str(node['loc'][1]))
self.defaultAttrs(nodeElem, node)
self.tagNodes(doc, nodeElem, node)
yield "%s\n" % (nodeElem.toxml('UTF-8'),)
if 'ways' in data:
for way in data['ways']:
wayElem = doc.createElement("way")
self.defaultAttrs(wayElem, way)
self.tagNodes(doc, wayElem, way)
for ref in way['nd']:
refElement = doc.createElement("nd")
refElement.setAttribute("ref", str(ref))
wayElem.appendChild(refElement)
yield "%s\n" % (wayElem.toxml('UTF-8'),)
if 'relations' in data:
for relation in data['relations']:
relationElem = doc.createElement("relation")
self.defaultAttrs(relationElem, relation)
self.tagNodes(doc, relationElem, relation)
for member in relation['mm']:
memberElem = doc.createElement("member")
memberElem.setAttribute("type", member['type'])
memberElem.setAttribute("ref", str(member['ref']))
memberElem.setAttribute("role", member['role'])
relationElem.appendChild(memberElem)
yield "%s\n" % (relationElem.toxml('UTF-8'),)
yield '</osm>\n'
import time, sys
import os
import urlparse
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound
class Mongosm(object):
def decodePolyline(self, encoded):
i = 0
lat = 0.0
lon = 0.0
points = []
while i < len(encoded):
b = 0
shift = 0
result = 0
while True:
b = ord(encoded[i]) - 63
i = i + 1
result |= (b & 0x1f) << shift
shift = shift + 5
if b < 0x20:
break
if (result & 1) > 0:
dlat = ~(result >> 1)
else:
dlat = (result >> 1)
lat = lat + dlat
shift = 0
result = 0
while True:
b = ord(encoded[i]) - 63
i = i + 1
result |= (b & 0x1f) << shift
shift = shift + 5
if b < 0x20:
break
if (result & 1) > 0:
dlng = ~(result >> 1)
else:
dlng = (result >> 1)
lon = lon + dlng
points.append([lat * 1e-5, lon * 1e-5])
return points
def buildMongoQuery(self, xapiQuery):
q = {}
groups = re.findall(r'(?:\[(.*?)\])', xapiQuery)
for g in groups:
(left, right) = g.split('=')
if left == '@user':
q['user'] = right
elif left == '@uid':
q['uid'] = long(right)
elif left is '@changeset':
q['changeset'] = long(right)
elif left == 'bbox':
(minlon, minlat, maxlon, maxlat) = right.split(',')
bboxPolygon = [ [float(minlat),float(minlon)],
[float(minlat),float(maxlon)],
[float(maxlat),float(maxlon)],
[float(maxlat),float(minlon)] ]
q['loc'] = { '$within': { '$polygon': bboxPolygon } }
elif left == 'poly':
decodedPolygon = self.decodePolyline(right)
q['loc'] = { '$within': { '$polygon': decodedPolygon } }
elif right == u'*':
q['tags.%s' % (left,)] = {'$exists': True}
else:
q['tags.%s' % (left,)] = right
print "Built query: %s" % (q,)
return q
def mapRequest(self, request):
#(minlon, minlat, maxlon, maxlat) = request.args['bbox'].split(',')
#bbox = [[float(minlat), float(minlon)],[float(maxlat), float(maxlon)]]
query = self.buildMongoQuery('[bbox=%s]' % (request.args['bbox'],))
api = OsmApi()
data = api.getBbox(query)
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml', direct_passthrough=True)
def changesetsRequest(self, request):
return Response("<boop>%s</boop>" % (xapi_query,))
def getNode(self, request, id):
api = OsmApi()
data = api.getNodeById(long(id))
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getNodeQuery(self, request, xapi_query):
query = self.buildMongoQuery(xapi_query)
api = OsmApi()
data = api.getNodes(query)
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getWay(self, request, id):
api = OsmApi()
data = api.getWayById(long(id))
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getWayQuery(self, request, xapi_query):
query = self.buildMongoQuery(xapi_query)
api = OsmApi()
data = api.getWays(query)
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getRelation(self, request, id):
api = OsmApi()
data = api.getRelationById(long(id))
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getRelationQuery(self, request, xapi_query):
query = self.buildMongoQuery(xapi_query)
api = OsmApi()
data = api.getRelations(query)
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def getPrimitiveQuery(self, request, xapi_query):
query = self.buildMongoQuery(xapi_query)
api = OsmApi()
data = api.getPrimitives(query)
outputter = OsmXmlOutput()
return Response(outputter.iter(data), content_type='text/xml')
def capabilitiesRequest(self, request):
return Response("""
<osm version="0.6" generator="mongosm 0.1">
<api>
<version minimum="0.6" maximum="0.6"/>
<area maximum="0.5"/>
</api>
</osm>""")
def __init__(self):
self.url_map = Map([
Rule('/api/0.6/map', endpoint='mapRequest'),
Rule('/api/0.6/changesets', endpoint='changesetsRequest'),
Rule('/api/0.6/node/<id>', endpoint='getNode'),
Rule('/api/0.6/way/<id>', endpoint='getWay'),
Rule('/api/0.6/relation/<id>', endpoint='getRelation'),
Rule('/api/0.6/node<xapi_query>', endpoint='getNodeQuery'),
Rule('/api/0.6/way<xapi_query>', endpoint='getWayQuery'),
Rule('/api/0.6/relation<xapi_query>', endpoint='getRelationQuery'),
Rule('/api/0.6/*<xapi_query>', endpoint='getPrimitiveQuery'),
Rule('/api/capabilities', endpoint='capabilitiesRequest'),
])
def dispatch_request(self, request):
adapter = self.url_map.bind_to_environ(request.environ)
try:
endpoint, values = adapter.match()
return getattr(self, endpoint)(request, **values)
except HTTPException, e:
return e
def wsgi_app(self, environ, start_response):
request = Request(environ)
response = self.dispatch_request(request)
return response(environ, start_response)
def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
if __name__ == '__main__':
from werkzeug.serving import run_simple
app = Mongosm()
run_simple('0.0.0.0', 5000, app, use_debugger=True, use_reloader=True)