-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathMap.py
More file actions
395 lines (335 loc) · 12.8 KB
/
Map.py
File metadata and controls
395 lines (335 loc) · 12.8 KB
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
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 21 16:18:49 2020
@author: The Absolute Tinkerer
This class is used to ingest an Open Source Map (osm extension) file. Map will
render lines (represented by QPen type) and fills (represented by QColor type)
but not points. Relations consist of Ways, which consist of Nodes.
"""
import xml.etree.ElementTree as ET
from PyQt5.QtGui import QPen, QColor, QPainterPath
from PyQt5.QtCore import QPointF
from Transform import Transform
import constants as c
class Node:
def __init__(self, attrib, transform):
"""
Constructor
"""
self._id = int(attrib['id'])
self._x = transform.convertLong(float(attrib['lon']))
self._y = transform.convertLat(float(attrib['lat']))
"""
###########################################################################
Properties
###########################################################################
"""
@property
def ID(self):
return self._id
@property
def x(self):
return self._x
@property
def y(self):
return self._y
class Way:
def __init__(self, parent):
"""
Constructor
"""
self._id = int(parent.attrib['id'])
self._nids = []
self._tags = {}
for child in parent:
if child.tag == 'nd':
self._nids.append(int(child.attrib['ref']))
elif child.tag == 'tag':
key, value = child.attrib['k'], child.attrib['v']
self._tags[key] = value
"""
###########################################################################
Properties
###########################################################################
"""
@property
def ID(self):
return self._id
@property
def NIDs(self):
return self._nids
@property
def tags(self):
return self._tags
class Relation:
def __init__(self, parent):
"""
Constructor
"""
self._id = parent.attrib['id']
self._wids = []
self._tags = {}
for child in parent:
if child.tag == 'member' and child.attrib['type'] == 'way':
self._wids.append(int(child.attrib['ref']))
elif child.tag == 'tag':
key, value = child.attrib['k'], child.attrib['v']
self._tags[key] = value
"""
###########################################################################
Properties
###########################################################################
"""
@property
def ID(self):
return self._id
@property
def WIDs(self):
return self._wids
@property
def tags(self):
return self._tags
class Map:
def __init__(self, width, height, fname, config, scale=1):
"""
Constructor
Parameters:
-----------
width : int
The width of the canvas we're displaying to the user; a separate
width will be used when saving the file
height : int
The height of the canvas we're displaying to the user; a
fname : String
The OSM file name
config : Configuration
The configuration file we use to get all relevant settings
scale : float
This determines how much you scale the pen widths. You want the
output image to look the same as the GUI, so we scale the pen
widths accordingly
"""
# Initial variables
root = ET.parse(fname).getroot()
transform = None
nodes = {}
ways = {}
relations = {}
for child in root:
if child.tag == 'node':
node = Node(child.attrib, transform)
nodes[node.ID] = node
elif child.tag == 'way':
way = Way(child)
ways[way.ID] = way
elif child.tag == 'relation':
relation = Relation(child)
relations[relation.ID] = relation
elif child.tag == 'bounds':
transform = Transform(float(child.attrib['minlat']),
float(child.attrib['maxlat']),
float(child.attrib['minlon']),
float(child.attrib['maxlon']),
width, height)
# Bind class variables
self._copyright = c.COPYRIGHT
self._attribution = c.ATTRIBUTION
self._license = c.LICENSE
self._transform = transform
self._nodes = nodes
self._ways = ways
self._relations = relations
self._fname = fname
self._scale = scale
self._config = config
"""
###########################################################################
Properties
###########################################################################
"""
@property
def Copyright(self):
return self._copyright
@property
def Attribution(self):
return self._attribution
@property
def License(self):
return self._license
@property
def fname(self):
return self._fname
"""
###########################################################################
Public Functions
###########################################################################
"""
def setTransform(self, transform):
"""
"""
self._transform = transform
def getTransform(self):
"""
"""
return self._transform
def draw(self, p):
"""
p : QPainter
"""
p.setRenderHint(p.Antialiasing)
# Simplification variables
w, h = self._transform.width, self._transform.height
xo, yo = self._transform.xOffset, self._transform.yOffset
# Color the background according to the settings file
p.fillRect(0, 0, w, h, self._config.getValue(c.CONFIG_BG_COLOR))
# Fill all natural relations
order = [c.KEY_NATURAL]
for ID in self._relations.keys():
rel = self._relations[ID]
for i, tag in enumerate(order):
try:
if(tag in rel.tags.keys() and self._config.getItemState(
c.DATA_GROUPS[tag][rel.tags[tag]])):
self._renderRelation(p, rel, tag)
except KeyError:
# See note in _buildQueue for details
s = '* WARNING: tag="%s"; key="%s"' % (tag, rel.tags[tag])
s += ' will not render unless manually added!'
print(s)
# build the drawing queue so we don't have multiple for loops
order = [c.KEY_LANDUSE, c.KEY_WATERWAY, c.KEY_NATURAL, c.KEY_HIGHWAY,
c.KEY_BUILDING]
queue = self._buildQueue(order)
# Draw the ways from the queue
for i, tag in enumerate(order):
for way in queue[i]:
self._render(p, way, tag)
# Lastly, color the out of bounds regions white: T, B, L, R
p.fillRect(0, 0, int(w), int(yo), QColor(255, 255, 255))
p.fillRect(0, int(h-yo), int(w), int(yo), QColor(255, 255, 255))
p.fillRect(0, 0, int(xo), int(h), QColor(255, 255, 255))
p.fillRect(int(w-xo), 0, int(xo), int(h), QColor(255, 255, 255))
"""
###########################################################################
Private Functions
###########################################################################
"""
def _buildQueue(self, order):
"""
Private function used to construct the paint order for elements. This
will do very basic ordering, and it's recommended to implement a tool
in the GUI to perform ordering in the future.
Parameters:
-----------
order : String
The KEY strings that determine in which order painting will be
completed, with first indices being rendered first
Returns:
--------
queue : List of Way lists
This will be a 2d array of Ways for each KEY
"""
queue = [[] for i in range(len(order))]
for ID in self._ways.keys():
way = self._ways[ID]
for i, tag in enumerate(order):
try:
if(tag in way.tags.keys() and self._config.getItemState(
c.DATA_GROUPS[tag][way.tags[tag]])):
queue[i].append(way)
except KeyError:
# User will need to add by the following
# 1) Create a unique VAL in constants.py
# 2) Create a unique CONFIG_STYLE in constants.py
# 3) Connect VAL and CONFIG_STYLE in the DATA_GROUPS data
# (constants.py file)
# 4) Connect the CONFIG_STYLE to a QPen or QColor in
# configuration.py
s = '* WARNING: tag="%s"; key="%s"' % (tag, way.tags[tag])
s += ' will not render unless manually added!'
print(s)
return queue
def _render(self, p, way, tag):
"""
Private function used to render the Way object passed in. Ways may be
filled or simply drawn, so the below code checks for a QPen (draw) vs.
a QColor (fill)
Parameters:
-----------
p : QPainter
The object with which we're drawing
way : Way
The meta object containing drawing information
tag : String
The tag string corresponding to 'natural', 'highway', 'waterway',
etc.
Returns:
--------
"""
# Select the style
styleKey = c.DATA_GROUPS[tag][way.tags[tag]]
value = self._config.getValue(styleKey)
points = []
for nid in way.NIDs:
points.append([self._nodes[nid].x,
self._nodes[nid].y])
if type(value) == QPen:
value.setWidthF(self._scale*value.widthF())
p.setPen(value)
path = QPainterPath(QPointF(*points[0]))
for x, y in points[1:]:
path.lineTo(QPointF(x, y))
p.drawPath(path)
elif type(value) == QColor:
path = QPainterPath(QPointF(*points[0]))
for x, y in points[1:-1]:
path.lineTo(QPointF(x, y))
path.closeSubpath()
p.fillPath(path, value)
def _renderRelation(self, p, relation, tag):
"""
Private function to render relations. Relations are just different from
ways that I constructed a separate function for them. Little bit of
code copy-paste, but not much
Parameters:
-----------
p : QPainter
The object with which we're drawing
relation : Relation
The meta object containing OSM Relation information
tag : String
The tag string corresponding to 'natural', 'highway', 'waterway',
etc.
Returns:
--------
"""
ways = []
for wid in relation.WIDs:
# return if we don't have the data for this relation
# Note, some OSM files don't include all of the ways that are in
# relations... kinda annoying actually
if wid in self._ways.keys():
ways.append(self._ways[wid])
else:
return
# Select the style
styleKey = c.DATA_GROUPS[tag][relation.tags[tag]]
value = self._config.getValue(styleKey)
path = QPainterPath()
# Trace out the ways using a QPainterPath
for way in ways:
points = []
for nid in way.NIDs:
points.append([self._nodes[nid].x,
self._nodes[nid].y])
path.moveTo(*points[0])
for x, y in points[1:]:
path.lineTo(x, y)
path.closeSubpath()
# Draw the ways via the QPainter
if type(value) == QPen:
value.setWidthF(self._scale*value.widthF())
p.setPen(value)
p.drawPath(path)
elif type(value) == QColor:
p.fillPath(path, value)