regions.py

Mon, 13 Aug 2018 22:13:39 +0300

author
Teemu Piippo <teemu@hecknology.net>
date
Mon, 13 Aug 2018 22:13:39 +0300
changeset 107
8bf031309f5d
parent 88
3b86597c5a88
child 109
88a5110b66ba
permissions
-rw-r--r--

updates

#!/usr/bin/env python3
from xml.etree import ElementTree
from geometry import *

def parse_nodes(root):
	nodes = {}
	for child in root:
		if child.tag == 'node':
			lat, lon = float(child.attrib['lat']), float(child.attrib['lon'])
			nodes[child.attrib['id']] = Location(lat, lon)
	return nodes

def parse_way(way, nodes):
	result = {'shape': [], 'name': None}
	for child in way:
		if child.tag == 'nd':
			result['shape'].append(child.attrib['ref'])
		elif child.tag == 'tag':
			if child.attrib['k'] == 'shape':
				raise ValueError('tag "shape" is not allowed')
			result[child.attrib['k']] = child.attrib['v']
	if result['shape'][-1] != result['shape'][0]:
		raise ValueError('polygon for %r is not closed' % result)
	result['shape'] = [nodes[ref] for ref in result['shape'][:-1]]
	result['shape'] = Polygon(*result['shape'])
	return result

def parse_regions(filename):
	tree = ElementTree.parse(filename)
	root = tree.getroot()
	nodes = parse_nodes(root)
	regions = {}
	for child in root:
		if child.tag == 'way':
			way = parse_way(child, nodes = nodes)
			if 'region' in way and 'name' in way:
				way['priority'] = int(way.get('priority', 1))
				regions[way['name']] = way
	return regions

mercurial