MCPcopy Create free account
hub / github.com/comaps/comaps / query_osm

Function query_osm

tools/python/mixed_to_geojson.py:41–100  ·  view source on GitHub ↗
(osm_type, osm_id)

Source from the content-addressed store, hash-verified

39
40
41def query_osm(osm_type, osm_id):
42 if os.path.exists(OSM_CACHE):
43 with open(OSM_CACHE, 'r') as f:
44 cache = json.load(f)
45 else:
46 cache = {}
47 k = '{}{}'.format(osm_type, osm_id)
48 if k in cache:
49 coord = cache[k]
50 return (coord[1], coord[0])
51
52 OSM_API_SERVER = 'https://api.openstreetmap.org/api/0.6'
53 try:
54 r = urllib.request.urlopen('{}/{}/{}{}'.format(
55 OSM_API_SERVER, osm_type, osm_id, '/full' if osm_type != 'node' else ''))
56 except OSError as e:
57 logging.warn('Could not download %s %s: %s', osm_type, osm_id, e)
58 return None
59 xml = etree.parse(r)
60 nodes = {}
61 for nd in xml.findall('node'):
62 nodes[nd.get('id')] = (float(nd.get('lat')), float(nd.get('lon')))
63 ways = {}
64 for way in xml.findall('way'):
65 coord = [0, 0]
66 count = 0
67 for nd in way.findall('nd'):
68 count += 1
69 for i in range(len(coord)):
70 coord[i] += nodes[nd.get('ref')][i]
71 ways[way.get('id')] = [coord[0] / count, coord[1] / count]
72
73 coord = None
74 if osm_type == 'node':
75 coord = nodes[str(osm_id)]
76 elif osm_type == 'way':
77 coord = ways[str(osm_id)]
78 else:
79 for el in xml.findall(osm_type):
80 if el.get('id') == str(osm_id):
81 coord = [0, 0]
82 count = 0
83 for m in el.findall('member'):
84 if m.get('type') == 'node' and m.get('ref') in nodes:
85 count += 1
86 for i in range(len(coord)):
87 coord[i] += nodes[m.get('ref')][i]
88 elif m.get('type') == 'way' and m.get('ref') in ways:
89 count += 1
90 for i in range(len(coord)):
91 coord[i] += ways[m.get('ref')][i]
92 if count > 0:
93 coord = [coord[0] / count, coord[1] / count]
94 if coord is None:
95 return None
96
97 cache[k] = coord
98 with open(OSM_CACHE, 'w') as f:

Callers 1

Calls 5

formatMethod · 0.80
dumpMethod · 0.80
getMethod · 0.65
loadMethod · 0.45
parseMethod · 0.45

Tested by

no test coverage detected