-
Notifications
You must be signed in to change notification settings - Fork 0
/
Map.py
374 lines (298 loc) · 12 KB
/
Map.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
#-----------------------------------------------------------------------------
#
# Map helper functions
#
# Copyright (C) 2018 Florian Pose
#
# This file is part of Alarm Display.
#
# Alarm Display is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Alarm Display is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# Alarm Display. If not, see <http://www.gnu.org/licenses/>.
#
#-----------------------------------------------------------------------------
import os
import math
import numpy as np
from PyQt5.QtGui import QPixmap, QPainter, QPolygonF, QPen, QColor
from PyQt5.QtCore import QPoint, QRect
import requests
import json
from Projection import MercatorProjection
#-----------------------------------------------------------------------------
tileDim = 256
#-----------------------------------------------------------------------------
def deg2num(lat_deg, lon_deg, zoom):
lat_rad = math.radians(lat_deg)
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((1.0 - math.log(math.tan(lat_rad) + \
(1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
return (xtile, ytile)
#-----------------------------------------------------------------------------
def num2deg(xtile, ytile, zoom):
"""
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
This returns the NW-corner of the square.
Use the function with xtile+1 and/or ytile+1 to get the other corners.
With xtile+0.5 & ytile+0.5 it will return the center of the tile.
"""
n = 2.0 ** zoom
lon_deg = xtile / n * 360.0 - 180.0
lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
lat_deg = math.degrees(lat_rad)
return (lat_deg, lon_deg)
#-----------------------------------------------------------------------------
def meters_per_pixel(zoom, lat_deg):
r = 6372798.2
C = 2 * math.pi * r
return C / (2 ** (zoom + 8)) # equator
#-----------------------------------------------------------------------------
def getTargetPixmap(lat_deg, lon_deg, width, height, route, config, logger):
zoom = config.getint("destination_map", "zoom", fallback = 17)
x, y = deg2num(lat_deg, lon_deg, zoom)
tile_lat_deg, tile_lon_deg = num2deg(x, y, zoom)
next_tile_lat_deg, next_tile_lon_deg = num2deg(x + 1, y + 1, zoom)
proj = MercatorProjection(tile_lon_deg, next_tile_lat_deg,
next_tile_lon_deg, tile_lat_deg)
coord = proj(lon_deg, lat_deg)
mpp = meters_per_pixel(zoom, lat_deg)
px = np.array(coord) / mpp
center = QPoint(int(width / 2), int(height / 2))
offset = QPoint(int(px[0]), int(tileDim - px[1]))
centerTilePoint = center - offset
xd = math.ceil(centerTilePoint.x() / tileDim)
if xd < 0:
xd = 0
minX = x - xd
yd = math.ceil(centerTilePoint.y() / tileDim)
if yd < 0:
yd = 0
minY = y - yd
originX = centerTilePoint.x() - xd * tileDim
originY = centerTilePoint.y() - yd * tileDim
numX = math.ceil((width - originX) / tileDim)
numY = math.ceil((height - originY) / tileDim)
totHeight = numY * tileDim
lllat, lllon = num2deg(minX, minY + numY, zoom)
urlat, urlon = num2deg(minX + numX, minY, zoom)
totProj = MercatorProjection(lllon, lllat, urlon, urlat)
pixmap = QPixmap(int(width), int(height))
pixmap.fill() # white
painter = QPainter()
painter.begin(pixmap)
for i in range(0, numX):
for j in range(0, numY):
tile = getTile(minX + i, minY + j, zoom, config, logger)
xp = originX + i * tileDim
yp = originY + j * tileDim
painter.drawPixmap(xp, yp, tile)
#painter.drawRect(xp, yp, tileDim, tileDim)
poly = QPolygonF()
for point in route:
coord = totProj(point[0], point[1])
px = np.array(coord) / mpp
pos = QPoint(originX + px[0], originY + totHeight - px[1])
poly.append(pos)
pen = QPen()
pen.setWidth(config.getint("destination_map", "route_width",
fallback = 7))
pen.setColor(QColor(config.get("maps", "route_color",
fallback = "#400000c0")))
painter.setPen(pen)
painter.drawPolyline(poly)
marker = QPixmap()
imageDir = config.get("display", "image_dir", fallback = "images")
marker.load(os.path.join(imageDir, config.get("maps",
"destination_marker", fallback = "marker_dest.png")))
markerOffset = QPoint(int(marker.width() / 2), marker.height())
painter.drawPixmap(center - markerOffset, marker)
painter.end()
return pixmap
#-----------------------------------------------------------------------------
def getRoutePixmap(dest_lat_deg, dest_lon_deg, width, height, route, config,
logger):
# Home / Start point
home_lon_deg = config.getfloat("route", "home_longitude",
fallback = 6.09806)
home_lat_deg = config.getfloat("route", "home_latitude",
fallback = 51.76059)
# mean shall be center
lat_deg = (home_lat_deg + dest_lat_deg) / 2
lon_deg = (home_lon_deg + dest_lon_deg) / 2
lat_cos = math.cos(math.radians(lat_deg))
marginFactor = 1.3
min_lon_deg = min(home_lon_deg, dest_lon_deg)
max_lon_deg = max(home_lon_deg, dest_lon_deg)
lon_diff = (max_lon_deg - min_lon_deg) * marginFactor
min_lat_deg = min(home_lat_deg, dest_lat_deg)
max_lat_deg = max(home_lat_deg, dest_lat_deg)
lat_diff = (max_lat_deg - min_lat_deg) * marginFactor / lat_cos
min_x_tiles = math.ceil(width / tileDim) + 1
min_y_tiles = math.ceil(height / tileDim) + 1
# n = 2 ** z
# M = al / 360 * 2 ** z
# 2 ** z = M * 360 / al
# z = log2(M * 360 / al)
zoom_x = math.log(min_x_tiles * 360.0 / lon_diff, 2.0)
zoom_y = math.log(min_y_tiles * 360.0 / lat_diff, 2.0)
zoom = round(min(zoom_x, zoom_y)) - 1
logger.debug('Zoom: %f x %f => %u', zoom_x, zoom_y, zoom)
max_zoom = config.getint("route", "max_zoom", fallback = 17)
lim_zoom = min(zoom, max_zoom)
if lim_zoom != zoom:
logger.debug('Limiting to %u', lim_zoom)
zoom = lim_zoom
mpp = meters_per_pixel(zoom, lat_deg)
x, y = deg2num(lat_deg, lon_deg, zoom)
tile_lat_deg, tile_lon_deg = num2deg(x, y, zoom)
next_tile_lat_deg, next_tile_lon_deg = num2deg(x + 1, y + 1, zoom)
proj = MercatorProjection(tile_lon_deg, next_tile_lat_deg,
next_tile_lon_deg, tile_lat_deg)
coord = proj(lon_deg, lat_deg)
px = np.array(coord) / mpp
center = QPoint(int(width / 2), int(height / 2))
offset = QPoint(int(px[0]), int(tileDim - px[1]))
centerTilePoint = center - offset
xd = math.ceil(centerTilePoint.x() / tileDim)
if xd < 0:
xd = 0
minX = x - xd
yd = math.ceil(centerTilePoint.y() / tileDim)
if yd < 0:
yd = 0
minY = y - yd
originX = centerTilePoint.x() - xd * tileDim
originY = centerTilePoint.y() - yd * tileDim
numX = math.ceil((width - originX) / tileDim)
numY = math.ceil((height - originY) / tileDim)
totHeight = numY * tileDim
lllat, lllon = num2deg(minX, minY + numY, zoom)
urlat, urlon = num2deg(minX + numX, minY, zoom)
totProj = MercatorProjection(lllon, lllat, urlon, urlat)
pixmap = QPixmap(int(width), int(height))
pixmap.fill() # white
painter = QPainter()
painter.begin(pixmap)
for i in range(0, numX):
for j in range(0, numY):
tile = getTile(minX + i, minY + j, zoom, config, logger)
xp = originX + i * tileDim
yp = originY + j * tileDim
painter.drawPixmap(xp, yp, tile)
#painter.drawRect(xp, yp, tileDim, tileDim)
poly = QPolygonF()
for point in route:
coord = totProj(point[0], point[1])
px = np.array(coord) / mpp
pos = QPoint(originX + px[0], originY + totHeight - px[1])
poly.append(pos)
pen = QPen()
pen.setWidth(config.getint("route_map", "route_width", fallback = 10))
pen.setColor(QColor(config.get("maps", "route_color",
fallback = "#400000c0")))
painter.setPen(pen)
painter.drawPolyline(poly)
markerRects = []
marker = QPixmap()
imageDir = config.get("display", "image_dir", fallback = "images")
marker.load(os.path.join(imageDir, config.get("maps", "home_marker",
fallback = "marker_home.png")))
markerOffset = QPoint(int(marker.width() / 2), marker.height())
coord = totProj(home_lon_deg, home_lat_deg)
px = np.array(coord) / mpp
pos = QPoint(int(originX + px[0]), int(originY + totHeight - px[1]))
markerPos = pos - markerOffset
painter.drawPixmap(markerPos, marker)
markerRect = QRect(markerPos, marker.size())
markerRects.append(markerRect)
marker.load(os.path.join(imageDir, config.get("maps",
"destination_marker", fallback = "marker_dest.png")))
markerOffset = QPoint(int(marker.width() / 2), marker.height())
coord = totProj(dest_lon_deg, dest_lat_deg)
px = np.array(coord) / mpp
pos = QPoint(int(originX + px[0]), int(originY + totHeight - px[1]))
markerPos = pos - markerOffset
painter.drawPixmap(markerPos, marker)
markerRect = QRect(markerPos, marker.size())
markerRects.append(markerRect)
painter.end()
return pixmap, markerRects
#-----------------------------------------------------------------------------
def getTile(x, y, zoom, config, logger):
tilesDir = config.get("maps", "tiles_dir", fallback = "tiles")
path = os.path.join(tilesDir, str(zoom), str(x), str(y) + '.png')
#logger.debug("Opening %s", path)
tile = QPixmap()
try:
tile.load(path)
except:
logger.debug("Couldn't open image %s", path)
return tile
#-----------------------------------------------------------------------------
def getRoute(dest_lat_deg, dest_lon_deg, config, logger):
# Home / Start point
home_lon_deg = config.getfloat("route", "home_longitude",
fallback = 6.09806)
home_lat_deg = config.getfloat("route", "home_latitude",
fallback = 51.76059)
api_key = config.get("route", "ors_api_key", fallback = "")
if not api_key:
# Abort, if no API key given
return ([], None, None)
headers = {
'Accept': 'application/geo+json; charset=utf-8',
'Authorization': api_key,
'Content-Type': 'application/json; charset=utf-8'
}
url = 'https://api.openrouteservice.org/v2/directions/driving-car/geojson'
body = {
"coordinates": [[home_lon_deg, home_lat_deg],
[dest_lon_deg, dest_lat_deg]],
"instructions": False,
}
try:
call = requests.post(url, json = body, headers = headers,
timeout = 5.0)
except:
logger.error('Route request failed.', exc_info = True)
return ([], None, None)
logger.debug('Received route response with status %u.', call.status_code)
try:
data = json.loads(call.text)
except:
logger.error('Failed to load route JSON.', exc_info = True)
return ([], None, None)
#logger.debug(json.dumps(data, sort_keys=True, indent = 4,
# separators = (',', ': ')))
try:
feature = data["features"][0]
except:
logger.error('Response feature not found.')
return ([], None, None)
try:
route = feature["geometry"]["coordinates"]
except:
logger.error('Route is empty.')
route = []
try:
distance = float(feature["properties"]["summary"]["distance"])
except:
logger.error('Distance is empty.')
distance = None
try:
duration = float(feature["properties"]["summary"]["duration"])
except:
logger.error('Duration is empty.')
duration = None
return (route, distance, duration)
#-----------------------------------------------------------------------------