regions.py

changeset 88
3b86597c5a88
child 109
88a5110b66ba
equal deleted inserted replaced
87:9139a94e540c 88:3b86597c5a88
1 #!/usr/bin/env python3
2 from xml.etree import ElementTree
3 from geometry import *
4
5 def parse_nodes(root):
6 nodes = {}
7 for child in root:
8 if child.tag == 'node':
9 lat, lon = float(child.attrib['lat']), float(child.attrib['lon'])
10 nodes[child.attrib['id']] = Location(lat, lon)
11 return nodes
12
13 def parse_way(way, nodes):
14 result = {'shape': [], 'name': None}
15 for child in way:
16 if child.tag == 'nd':
17 result['shape'].append(child.attrib['ref'])
18 elif child.tag == 'tag':
19 if child.attrib['k'] == 'shape':
20 raise ValueError('tag "shape" is not allowed')
21 result[child.attrib['k']] = child.attrib['v']
22 if result['shape'][-1] != result['shape'][0]:
23 raise ValueError('polygon for %r is not closed' % result)
24 result['shape'] = [nodes[ref] for ref in result['shape'][:-1]]
25 result['shape'] = Polygon(*result['shape'])
26 return result
27
28 def parse_regions(filename):
29 tree = ElementTree.parse(filename)
30 root = tree.getroot()
31 nodes = parse_nodes(root)
32 regions = {}
33 for child in root:
34 if child.tag == 'way':
35 way = parse_way(child, nodes = nodes)
36 if 'region' in way and 'name' in way:
37 way['priority'] = int(way.get('priority', 1))
38 regions[way['name']] = way
39 return regions

mercurial