-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapview_plus.py
More file actions
1281 lines (1097 loc) · 44.7 KB
/
mapview_plus.py
File metadata and controls
1281 lines (1097 loc) · 44.7 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#from main.py import MapView,MapMarker,MapLayer
MIN_LATITUDE = -90.
MAX_LATITUDE = 90.
MIN_LONGITUDE = -180.
MAX_LONGITUDE = 180.
CACHE_DIR = "cache"
# from mapview.types import Coordinate, Bbox
from collections import namedtuple
Coordinate = namedtuple("Coordinate", ["lat", "lon"])
class Bbox(tuple):
def collide(self, *args):
if isinstance(args[0], Coordinate):
coord = args[0]
lat = coord.lat
lon = coord.lon
else:
lat, lon = args
lat1, lon1, lat2, lon2 = self[:]
if lat1 < lat2:
in_lat = lat1 <= lat <= lat2
else:
in_lat = lat2 <= lat <= lat2
if lon1 < lon2:
in_lon = lon1 <= lon <= lon2
else:
in_lon = lon2 <= lon <= lon2
return in_lat and in_lon
# from mapview.source import MapSource
from kivy.metrics import dp
from math import cos, ceil, log, tan, pi, atan, exp
# from mapview import MIN_LONGITUDE, MAX_LONGITUDE, MIN_LATITUDE, MAX_LATITUDE, \
# CACHE_DIR
# from mapview.downloader import Downloader
from kivy.clock import Clock
from os.path import join, exists
from os import makedirs, environ
from concurrent.futures import ThreadPoolExecutor, TimeoutError, as_completed
from random import choice
import requests
import traceback
from time import time
# from mapview import CACHE_DIR
DEBUG = "MAPVIEW_DEBUG_DOWNLOADER" in environ
class Downloader(object):
_instance = None
MAX_WORKERS = 5
CAP_TIME = 0.064 # 15 FPS
@staticmethod
def instance(cache_dir):
if Downloader._instance is None:
if not cache_dir:
cache_dir = CACHE_DIR
Downloader._instance = Downloader(cache_dir=cache_dir)
return Downloader._instance
def __init__(self, max_workers=None, cap_time=None, **kwargs):
self.cache_dir = kwargs.get('cache_dir', CACHE_DIR)
if max_workers is None:
max_workers = Downloader.MAX_WORKERS
if cap_time is None:
cap_time = Downloader.CAP_TIME
super(Downloader, self).__init__()
self.is_paused = False
self.cap_time = cap_time
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self._futures = []
Clock.schedule_interval(self._check_executor, 1 / 60.)
if not exists(self.cache_dir):
makedirs(self.cache_dir)
def submit(self, f, *args, **kwargs):
future = self.executor.submit(f, *args, **kwargs)
self._futures.append(future)
def download_tile(self, tile):
if DEBUG:
print("Downloader: queue(tile) zoom={} x={} y={}".format(
tile.zoom, tile.tile_x, tile.tile_y))
future = self.executor.submit(self._load_tile, tile)
self._futures.append(future)
def download(self, url, callback, **kwargs):
if DEBUG:
print("Downloader: queue(url) {}".format(url))
future = self.executor.submit(
self._download_url, url, callback, kwargs)
self._futures.append(future)
def _download_url(self, url, callback, kwargs):
if DEBUG:
print("Downloader: download(url) {}".format(url))
r = requests.get(url, **kwargs)
return callback, (url, r,)
def _load_tile(self, tile):
if tile.state == "done":
return
cache_fn = tile.cache_fn
if exists(cache_fn):
if DEBUG:
print("Downloader: use cache {}".format(cache_fn))
return tile.set_source, (cache_fn,)
tile_y = tile.map_source.get_row_count(tile.zoom) - tile.tile_y - 1
uri = tile.map_source.url.format(z=tile.zoom, x=tile.tile_x, y=tile_y,
s=choice(tile.map_source.subdomains))
if DEBUG:
print("Downloader: download(tile) {}".format(uri))
req = requests.get(uri, timeout=5)
try:
req.raise_for_status()
data = req.content
with open(cache_fn, "wb") as fd:
fd.write(data)
if DEBUG:
print("Downloaded {} bytes: {}".format(len(data), uri))
return tile.set_source, (cache_fn,)
except Exception as e:
print("Downloader error: {!r}".format(e))
def _check_executor(self, dt):
start = time()
try:
for future in as_completed(self._futures[:], 0):
self._futures.remove(future)
try:
result = future.result()
except Exception:
traceback.print_exc()
# make an error tile?
continue
if result is None:
continue
callback, args = result
callback(*args)
# capped executor in time, in order to prevent too much
# slowiness.
# seems to works quite great with big zoom-in/out
if time() - start > self.cap_time:
break
except TimeoutError:
pass
# from mapview.utils import clamp
def clamp(x, minimum, maximum):
return max(minimum, min(x, maximum))
import hashlib
class MapSource(object):
"""Base class for implementing a map source / provider
"""
attribution_osm = 'Maps & Data © [i][ref=http://www.osm.org/copyright]OpenStreetMap contributors[/ref][/i]'
attribution_thunderforest = 'Maps © [i][ref=http://www.thunderforest.com]Thunderforest[/ref][/i], Data © [i][ref=http://www.osm.org/copyright]OpenStreetMap contributors[/ref][/i]'
# list of available providers
# cache_key: (is_overlay, minzoom, maxzoom, url, attribution)
providers = {
"osm": (0, 0, 19, "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", attribution_osm),
"osm-hot": (0, 0, 19, "http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png", ""),
"osm-de": (0, 0, 18, "http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png", "Tiles @ OSM DE"),
"osm-fr": (0, 0, 20, "http://{s}.tile.openstreetmap.fr/osmfr/{z}/{x}/{y}.png", "Tiles @ OSM France"),
"cyclemap": (0, 0, 17, "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png", "Tiles @ Andy Allan"),
"thunderforest-cycle": (
0, 0, 19, "http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png", attribution_thunderforest),
"thunderforest-transport": (
0, 0, 19, "http://{s}.tile.thunderforest.com/transport/{z}/{x}/{y}.png", attribution_thunderforest),
"thunderforest-landscape": (
0, 0, 19, "http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png", attribution_thunderforest),
"thunderforest-outdoors": (
0, 0, 19, "http://{s}.tile.thunderforest.com/outdoors/{z}/{x}/{y}.png", attribution_thunderforest),
# no longer available
# "mapquest-osm": (0, 0, 19, "http://otile{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.jpeg", "Tiles Courtesy of Mapquest", {"subdomains": "1234", "image_ext": "jpeg"}),
# "mapquest-aerial": (0, 0, 19, "http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpeg", "Tiles Courtesy of Mapquest", {"subdomains": "1234", "image_ext": "jpeg"}),
# more to add with
# https://github.com/leaflet-extras/leaflet-providers/blob/master/leaflet-providers.js
# not working ?
# "openseamap": (0, 0, 19, "http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png",
# "Map data @ OpenSeaMap contributors"),
}
def __init__(self,
url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
cache_key=None, min_zoom=0, max_zoom=19, tile_size=256,
image_ext="png",
attribution="© OpenStreetMap contributors",
subdomains="abc", **kwargs):
super(MapSource, self).__init__()
if cache_key is None:
# possible cache hit, but very unlikely
cache_key = hashlib.sha224(url.encode("utf8")).hexdigest()[:10]
self.url = url
self.cache_key = cache_key
self.min_zoom = min_zoom
self.max_zoom = max_zoom
self.tile_size = tile_size
self.image_ext = image_ext
self.attribution = attribution
self.subdomains = subdomains
self.cache_fmt = "{cache_key}_{zoom}_{tile_x}_{tile_y}.{image_ext}"
self.dp_tile_size = min(dp(self.tile_size), self.tile_size * 2)
self.default_lat = self.default_lon = self.default_zoom = None
self.bounds = None
self.cache_dir = kwargs.get('cache_dir', CACHE_DIR)
@staticmethod
def from_provider(key, **kwargs):
provider = MapSource.providers[key]
cache_dir = kwargs.get('cache_dir', CACHE_DIR)
options = {}
is_overlay, min_zoom, max_zoom, url, attribution = provider[:5]
if len(provider) > 5:
options = provider[5]
return MapSource(cache_key=key, min_zoom=min_zoom,
max_zoom=max_zoom, url=url, cache_dir=cache_dir,
attribution=attribution, **options)
def get_x(self, zoom, lon):
"""Get the x position on the map using this map source's projection
(0, 0) is located at the top left.
"""
lon = clamp(lon, MIN_LONGITUDE, MAX_LONGITUDE)
return ((lon + 180.) / 360. * pow(2., zoom)) * self.dp_tile_size
def get_y(self, zoom, lat):
"""Get the y position on the map using this map source's projection
(0, 0) is located at the top left.
"""
lat = clamp(-lat, MIN_LATITUDE, MAX_LATITUDE)
lat = lat * pi / 180.
return ((1.0 - log(tan(lat) + 1.0 / cos(lat)) / pi) / \
2. * pow(2., zoom)) * self.dp_tile_size
def get_lon(self, zoom, x):
"""Get the longitude to the x position in the map source's projection
"""
dx = x / float(self.dp_tile_size)
lon = dx / pow(2., zoom) * 360. - 180.
return clamp(lon, MIN_LONGITUDE, MAX_LONGITUDE)
def get_lat(self, zoom, y):
"""Get the latitude to the y position in the map source's projection
"""
dy = y / float(self.dp_tile_size)
n = pi - 2 * pi * dy / pow(2., zoom)
lat = -180. / pi * atan(.5 * (exp(n) - exp(-n)))
return clamp(lat, MIN_LATITUDE, MAX_LATITUDE)
def get_row_count(self, zoom):
"""Get the number of tiles in a row at this zoom level
"""
if zoom == 0:
return 1
return 2 << (zoom - 1)
def get_col_count(self, zoom):
"""Get the number of tiles in a col at this zoom level
"""
if zoom == 0:
return 1
return 2 << (zoom - 1)
def get_min_zoom(self):
"""Return the minimum zoom of this source
"""
return self.min_zoom
def get_max_zoom(self):
"""Return the maximum zoom of this source
"""
return self.max_zoom
def fill_tile(self, tile):
"""Add this tile to load within the downloader
"""
if tile.state == "done":
return
Downloader.instance(cache_dir=self.cache_dir).download_tile(tile)
# from mapview.view import MapView, MapMarker, MapLayer, MarkerMapLayer, \
# MapMarkerPopup
# coding=utf-8
from os.path import join, dirname
from kivy.clock import Clock
from kivy.metrics import dp
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.scatter import Scatter
from kivy.uix.behaviors import ButtonBehavior
from kivy.properties import NumericProperty, ObjectProperty, ListProperty, \
AliasProperty, BooleanProperty, StringProperty
from kivy.graphics import Canvas, Color, Rectangle
from kivy.graphics.transformation import Matrix
from kivy.lang import Builder
from kivy.compat import string_types
from math import ceil
# from mapview import MIN_LONGITUDE, MAX_LONGITUDE, MIN_LATITUDE, MAX_LATITUDE, \
# CACHE_DIR, Coordinate, Bbox
# from mapview.source import MapSource
# from mapview.utils import clamp
from itertools import takewhile
import webbrowser
Builder.load_string("""
<MapMarker>:
size_hint: None, None
source: root.source
size: list(map(dp, self.texture_size))
allow_stretch: True
<MapView>:
canvas.before:
StencilPush
Rectangle:
pos: self.pos
size: self.size
StencilUse
Color:
rgba: self.background_color
Rectangle:
pos: self.pos
size: self.size
canvas.after:
StencilUnUse
Rectangle:
pos: self.pos
size: self.size
StencilPop
ClickableLabel:
text: root.map_source.attribution if hasattr(root.map_source, "attribution") else ""
size_hint: None, None
size: self.texture_size[0] + sp(8), self.texture_size[1] + sp(4)
font_size: "10sp"
right: [root.right, self.center][0]
color: 0, 0, 0, 1
markup: True
canvas.before:
Color:
rgba: .8, .8, .8, .8
Rectangle:
pos: self.pos
size: self.size
<MapViewScatter>:
auto_bring_to_front: False
do_rotation: False
scale_min: 0.2
scale_max: 3.
<MapMarkerPopup>:
RelativeLayout:
id: placeholder
y: root.top
center_x: root.center_x
size: root.popup_size
""")
class ClickableLabel(Label):
def on_ref_press(self, *args):
webbrowser.open(str(args[0]), new=2)
class Tile(Rectangle):
def __init__(self, *args, **kwargs):
super(Tile, self).__init__(*args, **kwargs)
self.cache_dir = kwargs.get('cache_dir', CACHE_DIR)
@property
def cache_fn(self):
map_source = self.map_source
fn = map_source.cache_fmt.format(
image_ext=map_source.image_ext,
cache_key=map_source.cache_key,
**self.__dict__)
return join(self.cache_dir, fn)
def set_source(self, cache_fn):
self.source = cache_fn
self.state = "need-animation"
class MapMarker(ButtonBehavior, Image):
"""A marker on a map, that must be used on a :class:`MapMarker`
"""
anchor_x = NumericProperty(0.5)
"""Anchor of the marker on the X axis. Defaults to 0.5, mean the anchor will
be at the X center of the image.
"""
anchor_y = NumericProperty(0)
"""Anchor of the marker on the Y axis. Defaults to 0, mean the anchor will
be at the Y bottom of the image.
"""
lat = NumericProperty(0)
"""Latitude of the marker
"""
lon = NumericProperty(0)
"""Longitude of the marker
"""
source = StringProperty(join(dirname(__file__), "icons", "marker.png"))
"""Source of the marker, defaults to our own marker.png
"""
# (internal) reference to its layer
_layer = None
def detach(self):
if self._layer:
self._layer.remove_widget(self)
self._layer = None
class MapMarkerPopup(MapMarker):
is_open = BooleanProperty(False)
placeholder = ObjectProperty(None)
popup_size = ListProperty([100, 100])
def add_widget(self, widget):
if not self.placeholder:
self.placeholder = widget
if self.is_open:
super(MapMarkerPopup, self).add_widget(self.placeholder)
else:
self.placeholder.add_widget(widget)
def remove_widget(self, widget):
if widget is not self.placeholder:
self.placeholder.remove_widget(widget)
else:
super(MapMarkerPopup, self).remove_widget(widget)
def on_is_open(self, *args):
self.refresh_open_status()
def on_release(self, *args):
self.is_open = not self.is_open
def refresh_open_status(self):
if not self.is_open and self.placeholder.parent:
super(MapMarkerPopup, self).remove_widget(self.placeholder)
elif self.is_open and not self.placeholder.parent:
super(MapMarkerPopup, self).add_widget(self.placeholder)
class MapLayer(Widget):
"""A map layer, that is repositionned everytime the :class:`MapView` is
moved.
"""
viewport_x = NumericProperty(0)
viewport_y = NumericProperty(0)
def reposition(self):
"""Function called when :class:`MapView` is moved. You must recalculate
the position of your children.
"""
pass
def unload(self):
"""Called when the view want to completly unload the layer.
"""
pass
class MarkerMapLayer(MapLayer):
"""A map layer for :class:`MapMarker`
"""
order_marker_by_latitude = BooleanProperty(True)
def __init__(self, **kwargs):
self.markers = []
super(MarkerMapLayer, self).__init__(**kwargs)
def insert_marker(self, marker, **kwargs):
if self.order_marker_by_latitude:
before = list(takewhile(
lambda i_m: i_m[1].lat < marker.lat,
enumerate(self.children)
))
if before:
kwargs['index'] = before[-1][0] + 1
super(MarkerMapLayer, self).add_widget(marker, **kwargs)
def add_widget(self, marker):
marker._layer = self
self.markers.append(marker)
self.insert_marker(marker)
def remove_widget(self, marker):
marker._layer = None
if marker in self.markers:
self.markers.remove(marker)
super(MarkerMapLayer, self).remove_widget(marker)
def reposition(self):
if not self.markers:
return
mapview = self.parent
set_marker_position = self.set_marker_position
bbox = None
latest_bbox_size = dp(48)
# reposition the markers depending the latitude
markers = sorted(self.markers, key=lambda x: -x.lat)
margin = max((max(marker.size) for marker in markers))
bbox = mapview.get_bbox(margin)
for marker in markers:
if bbox.collide(marker.lat, marker.lon):
set_marker_position(mapview, marker)
if not marker.parent:
self.insert_marker(marker)
else:
super(MarkerMapLayer, self).remove_widget(marker)
def set_marker_position(self, mapview, marker):
x, y = mapview.get_window_xy_from(marker.lat, marker.lon, mapview.zoom)
marker.x = int(x - marker.width * marker.anchor_x)
marker.y = int(y - marker.height * marker.anchor_y)
def unload(self):
self.clear_widgets()
del self.markers[:]
class MapViewScatter(Scatter):
# internal
def on_transform(self, *args):
super(MapViewScatter, self).on_transform(*args)
self.parent.on_transform(self.transform)
def collide_point(self, x, y):
# print "collide_point", x, y
return True
class MapView(Widget):
"""MapView is the widget that control the map displaying, navigation, and
layers management.
"""
lon = NumericProperty()
"""Longitude at the center of the widget
"""
lat = NumericProperty()
"""Latitude at the center of the widget
"""
zoom = NumericProperty(0)
"""Zoom of the widget. Must be between :meth:`MapSource.get_min_zoom` and
:meth:`MapSource.get_max_zoom`. Default to 0.
"""
map_source = ObjectProperty(MapSource())
"""Provider of the map, default to a empty :class:`MapSource`.
"""
double_tap_zoom = BooleanProperty(False)
"""If True, this will activate the double-tap to zoom.
"""
pause_on_action = BooleanProperty(True)
"""Pause any map loading / tiles loading when an action is done.
This allow better performance on mobile, but can be safely deactivated on
desktop.
"""
snap_to_zoom = BooleanProperty(True)
"""When the user initiate a zoom, it will snap to the closest zoom for
better graphics. The map can be blur if the map is scaled between 2 zoom.
Default to True, even if it doesn't fully working yet.
"""
animation_duration = NumericProperty(100)
"""Duration to animate Tiles alpha from 0 to 1 when it's ready to show.
Default to 100 as 100ms. Use 0 to deactivate.
"""
delta_x = NumericProperty(0)
delta_y = NumericProperty(0)
background_color = ListProperty([181 / 255., 208 / 255., 208 / 255., 1])
cache_dir = StringProperty(CACHE_DIR)
_zoom = NumericProperty(0)
_pause = BooleanProperty(False)
_scale = 1.
_disabled_count = 0
__events__ = ["on_map_relocated"]
# Public API
@property
def viewport_pos(self):
vx, vy = self._scatter.to_local(self.x, self.y)
return vx - self.delta_x, vy - self.delta_y
@property
def scale(self):
if self._invalid_scale:
self._invalid_scale = False
self._scale = self._scatter.scale
return self._scale
def get_bbox(self, margin=0):
"""Returns the bounding box from the bottom/left (lat1, lon1) to
top/right (lat2, lon2).
"""
x1, y1 = self.to_local(0 - margin, 0 - margin)
x2, y2 = self.to_local((self.width + margin),
(self.height + margin))
c1 = self.get_latlon_at(x1, y1)
c2 = self.get_latlon_at(x2, y2)
return Bbox((c1.lat, c1.lon, c2.lat, c2.lon))
bbox = AliasProperty(get_bbox, None, bind=["lat", "lon", "_zoom"])
def unload(self):
"""Unload the view and all the layers.
It also cancel all the remaining downloads.
"""
self.remove_all_tiles()
def get_window_xy_from(self, lat, lon, zoom):
"""Returns the x/y position in the widget absolute coordinates
from a lat/lon"""
scale = self.scale
vx, vy = self.viewport_pos
ms = self.map_source
x = ms.get_x(zoom, lon) - vx
y = ms.get_y(zoom, lat) - vy
x *= scale
y *= scale
x = x + self.pos[0]
y = y + self.pos[1]
return x, y
def center_on(self, *args):
"""Center the map on the coordinate :class:`Coordinate`, or a (lat, lon)
"""
map_source = self.map_source
zoom = self._zoom
if len(args) == 1 and isinstance(args[0], Coordinate):
coord = args[0]
lat = coord.lat
lon = coord.lon
elif len(args) == 2:
lat, lon = args
else:
raise Exception("Invalid argument for center_on")
lon = clamp(lon, MIN_LONGITUDE, MAX_LONGITUDE)
lat = clamp(lat, MIN_LATITUDE, MAX_LATITUDE)
scale = self._scatter.scale
x = map_source.get_x(zoom, lon) - self.center_x / scale
y = map_source.get_y(zoom, lat) - self.center_y / scale
self.delta_x = -x
self.delta_y = -y
self.lon = lon
self.lat = lat
self._scatter.pos = 0, 0
self.trigger_update(True)
def set_zoom_at(self, zoom, x, y, scale=None):
"""Sets the zoom level, leaving the (x, y) at the exact same point
in the view.
"""
zoom = clamp(zoom,
self.map_source.get_min_zoom(),
self.map_source.get_max_zoom())
if int(zoom) == int(self._zoom):
if scale is None:
return
elif scale == self.scale:
return
scale = scale or 1.
# first, rescale the scatter
scatter = self._scatter
scale = clamp(scale, scatter.scale_min, scatter.scale_max)
rescale = scale * 1.0 / scatter.scale
scatter.apply_transform(Matrix().scale(rescale, rescale, rescale),
post_multiply=True,
anchor=scatter.to_local(x, y))
# adjust position if the zoom changed
c1 = self.map_source.get_col_count(self._zoom)
c2 = self.map_source.get_col_count(zoom)
if c1 != c2:
f = float(c2) / float(c1)
self.delta_x = scatter.x + self.delta_x * f
self.delta_y = scatter.y + self.delta_y * f
# back to 0 every time
scatter.apply_transform(Matrix().translate(
-scatter.x, -scatter.y, 0
), post_multiply=True)
# avoid triggering zoom changes.
self._zoom = zoom
self.zoom = self._zoom
def on_zoom(self, instance, zoom):
if zoom == self._zoom:
return
x = self.map_source.get_x(zoom, self.lon) - self.delta_x
y = self.map_source.get_y(zoom, self.lat) - self.delta_y
self.set_zoom_at(zoom, x, y)
self.center_on(self.lat, self.lon)
def get_latlon_at(self, x, y, zoom=None):
"""Return the current :class:`Coordinate` within the (x, y) widget
coordinate.
"""
if zoom is None:
zoom = self._zoom
vx, vy = self.viewport_pos
scale = self._scale
return Coordinate(
lat=self.map_source.get_lat(zoom, y / scale + vy),
lon=self.map_source.get_lon(zoom, x / scale + vx))
def add_marker(self, marker, layer=None):
"""Add a marker into the layer. If layer is None, it will be added in
the default marker layer. If there is no default marker layer, a new
one will be automatically created
"""
if layer is None:
if not self._default_marker_layer:
layer = MarkerMapLayer()
self.add_layer(layer)
else:
layer = self._default_marker_layer
layer.add_widget(marker)
layer.set_marker_position(self, marker)
def remove_marker(self, marker):
"""Remove a marker from its layer
"""
marker.detach()
def add_layer(self, layer, mode="window"):
"""Add a new layer to update at the same time the base tile layer.
mode can be either "scatter" or "window". If "scatter", it means the
layer will be within the scatter transformation. It's perfect if you
want to display path / shape, but not for text.
If "window", it will have no transformation. You need to position the
widget yourself: think as Z-sprite / billboard.
Defaults to "window".
"""
assert (mode in ("scatter", "window"))
if self._default_marker_layer is None and \
isinstance(layer, MarkerMapLayer):
self._default_marker_layer = layer
self._layers.append(layer)
c = self.canvas
if mode == "scatter":
self.canvas = self.canvas_layers
else:
self.canvas = self.canvas_layers_out
layer.canvas_parent = self.canvas
super(MapView, self).add_widget(layer)
self.canvas = c
def remove_layer(self, layer):
"""Remove the layer
"""
c = self.canvas
self._layers.remove(layer)
self.canvas = layer.canvas_parent
super(MapView, self).remove_widget(layer)
self.canvas = c
def sync_to(self, other):
"""Reflect the lat/lon/zoom of the other MapView to the current one.
"""
if self._zoom != other._zoom:
self.set_zoom_at(other._zoom, *self.center)
self.center_on(other.get_latlon_at(*self.center))
# Private API
def __init__(self, **kwargs):
from kivy.base import EventLoop
EventLoop.ensure_window()
self._invalid_scale = True
self._tiles = []
self._tiles_bg = []
self._tilemap = {}
self._layers = []
self._default_marker_layer = None
self._need_redraw_all = False
self._transform_lock = False
self.trigger_update(True)
self.canvas = Canvas()
self._scatter = MapViewScatter()
self.add_widget(self._scatter)
with self._scatter.canvas:
self.canvas_map = Canvas()
self.canvas_layers = Canvas()
with self.canvas:
self.canvas_layers_out = Canvas()
self._scale_target_anim = False
self._scale_target = 1.
self._touch_count = 0
self.map_source.cache_dir = self.cache_dir
Clock.schedule_interval(self._animate_color, 1 / 60.)
self.lat = kwargs.get("lat", self.lat)
self.lon = kwargs.get("lon", self.lon)
super(MapView, self).__init__(**kwargs)
def _animate_color(self, dt):
# fast path
d = self.animation_duration
if d == 0:
for tile in self._tiles:
if tile.state == "need-animation":
tile.g_color.a = 1.
tile.state = "animated"
for tile in self._tiles_bg:
if tile.state == "need-animation":
tile.g_color.a = 1.
tile.state = "animated"
else:
d = d / 1000.
for tile in self._tiles:
if tile.state != "need-animation":
continue
tile.g_color.a += dt / d
if tile.g_color.a >= 1:
tile.state = "animated"
for tile in self._tiles_bg:
if tile.state != "need-animation":
continue
tile.g_color.a += dt / d
if tile.g_color.a >= 1:
tile.state = "animated"
def add_widget(self, widget):
if isinstance(widget, MapMarker):
self.add_marker(widget)
elif isinstance(widget, MapLayer):
self.add_layer(widget)
else:
super(MapView, self).add_widget(widget)
def remove_widget(self, widget):
if isinstance(widget, MapMarker):
self.remove_marker(widget)
elif isinstance(widget, MapLayer):
self.remove_layer(widget)
else:
super(MapView, self).remove_widget(widget)
def on_map_relocated(self, zoom, coord):
pass
def animated_diff_scale_at(self, d, x, y):
self._scale_target_time = 1.
self._scale_target_pos = x, y
if self._scale_target_anim == False:
self._scale_target_anim = True
self._scale_target = d
else:
self._scale_target += d
Clock.unschedule(self._animate_scale)
Clock.schedule_interval(self._animate_scale, 1 / 60.)
def _animate_scale(self, dt):
diff = self._scale_target / 3.
if abs(diff) < 0.01:
diff = self._scale_target
self._scale_target = 0
else:
self._scale_target -= diff
self._scale_target_time -= dt
self.diff_scale_at(diff, *self._scale_target_pos)
ret = self._scale_target != 0
if not ret:
self._pause = False
return ret
def diff_scale_at(self, d, x, y):
scatter = self._scatter
scale = scatter.scale * (2 ** d)
self.scale_at(scale, x, y)
def scale_at(self, scale, x, y):
scatter = self._scatter
scale = clamp(scale, scatter.scale_min, scatter.scale_max)
rescale = scale * 1.0 / scatter.scale
scatter.apply_transform(Matrix().scale(rescale, rescale, rescale),
post_multiply=True,
anchor=scatter.to_local(x, y))
def on_touch_down(self, touch):
if not self.collide_point(*touch.pos):
return
if self.pause_on_action:
self._pause = True
if "button" in touch.profile and touch.button in (
"scrolldown", "scrollup"):
d = 1 if touch.button == "scrollup" else -1
self.animated_diff_scale_at(d, *touch.pos)
return True
elif touch.is_double_tap and self.double_tap_zoom:
self.animated_diff_scale_at(1, *touch.pos)
return True
touch.grab(self)
self._touch_count += 1
if self._touch_count == 1:
self._touch_zoom = (self.zoom, self._scale)
return super(MapView, self).on_touch_down(touch)
def on_touch_up(self, touch):
if touch.grab_current == self:
touch.ungrab(self)
self._touch_count -= 1
if self._touch_count == 0:
# animate to the closest zoom
zoom, scale = self._touch_zoom
cur_zoom = self.zoom
cur_scale = self._scale
if cur_zoom < zoom or cur_scale < scale:
self.animated_diff_scale_at(1. - cur_scale, *touch.pos)
elif cur_zoom > zoom or cur_scale > scale:
self.animated_diff_scale_at(2. - cur_scale, *touch.pos)
self._pause = False
return True
return super(MapView, self).on_touch_up(touch)
def on_transform(self, *args):
self._invalid_scale = True
if self._transform_lock:
return
self._transform_lock = True
# recalculate viewport
map_source = self.map_source
zoom = self._zoom
scatter = self._scatter
scale = scatter.scale
if scale >= 2.:
zoom += 1
scale /= 2.
elif scale < 1:
zoom -= 1
scale *= 2.
zoom = clamp(zoom, map_source.min_zoom, map_source.max_zoom)
if zoom != self._zoom:
self.set_zoom_at(zoom, scatter.x, scatter.y, scale=scale)
self.trigger_update(True)
else:
if zoom == map_source.min_zoom and scatter.scale < 1.:
scatter.scale = 1.
self.trigger_update(True)
else:
self.trigger_update(False)
if map_source.bounds:
self._apply_bounds()
self._transform_lock = False
self._scale = self._scatter.scale
def _apply_bounds(self):
# if the map_source have any constraints, apply them here.
map_source = self.map_source
zoom = self._zoom
min_lon, min_lat, max_lon, max_lat = map_source.bounds
xmin = map_source.get_x(zoom, min_lon)
xmax = map_source.get_x(zoom, max_lon)