-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path_webmap.py
1228 lines (984 loc) · 40.1 KB
/
_webmap.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
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 functools import lru_cache, partial
from warnings import warn, filterwarnings, catch_warnings
from types import SimpleNamespace
from PIL import Image
from io import BytesIO
from pprint import PrettyPrinter
from cartopy.io.img_tiles import GoogleWTS
from cartopy import crs as ccrs
import numpy as np
from pyproj import CRS, Transformer
from owslib.wmts import WebMapTileService
from owslib.wms import WebMapService
import requests
from urllib3.exceptions import InsecureRequestWarning
from .helpers import _sanitize
from cartopy.io import ogc_clients
from cartopy.io import RasterSource
from cartopy.io.ogc_clients import _target_extents
class _WebMap_layer:
# base class for adding methods to the _wms_layer- and wmts_layer objects
def __init__(self, m, wms, name):
self._m = m
self.name = name
self._wms = wms
self.wms_layer = self._wms.contents[name]
styles = list(self.wms_layer.styles)
if len(styles) == 0:
self._style = ""
else:
self._style = "default" if "default" in styles else styles[0]
# hardcode support for EPSG:3857 == GOOGLE_MERCATOR for now since cartopy
# hardcoded only EPSG:900913
# (see from cartopy.io.ogc_clients import _CRS_TO_OGC_SRS)
if hasattr(self.wms_layer, "crsOptions"):
if "EPSG:3857" in self.wms_layer.crsOptions:
ogc_clients._CRS_TO_OGC_SRS[ccrs.GOOGLE_MERCATOR] = "EPSG:3857"
if "epsg:3857" in self.wms_layer.crsOptions:
ogc_clients._CRS_TO_OGC_SRS[ccrs.GOOGLE_MERCATOR] = "epsg:3857"
@property
def info(self):
"""
pretty-print the available properties of the wms_layer to the console
"""
txt = ""
for key, val in self.wms_layer.__dict__.items():
if not val:
continue
p = PrettyPrinter(depth=1, indent=len(key) + 4, width=60 - len(key))
s = p.pformat(val).split("\n")
s = "\n".join([s[0].replace(" " * (len(key) + 3), ""), *s[1:]])
txt += f"{key} : {s}\n"
try:
if any(("legend" in val for key, val in self.wms_layer.styles.items())):
legQ = True
else:
legQ = False
except Exception:
legQ = False
print(f"\n LEGEND available: {legQ}\n\n" + txt)
def fetch_legend(self, style=None, silent=True):
if style is None:
style = self._style
try:
url = self.wms_layer.styles[style]["legend"]
legend = requests.get(url)
if url.endswith(".svg"):
try:
import cairosvg
img = cairosvg.svg2png(legend.content)
except ImportError:
warn("EOmaps: the legend is '.svg'... please install 'cairosvg'")
return None
else:
img = legend.content
img = Image.open(BytesIO(img))
except Exception:
if not silent:
warn("EOmaps: could not fetch the legend")
return None
return img
def add_legend(self, style=None, img=None):
"""
Add a legend to the plot (if available)
If you click on the legend you can drag it around!
The size of the legend can be changed by turning the mouse-wheel
while clicking on the legend.
Parameters
----------
style : str, optional
The style to use. The default is "default".
img : BytesIO
A pre-fetched legend (if provided the "style" kwarg is ignored!)
Returns
-------
legax : matpltolib.axes
The axes-object.
"""
from matplotlib.transforms import Bbox
if style is None:
style = self._style
self._legend_picked = False
if img is None:
legend = self.fetch_legend()
else:
legend = img
if legend is not None:
if not hasattr(self, "_layer"):
# use the currently active layer if the webmap service has not yet
# been added to the map
print("EOmaps: The WebMap for the legend is not yet added to the map!")
self._layer = self._m.BM._bg_layer
axpos = self._m.ax.get_position()
legax = self._m.f.add_axes((axpos.x0, axpos.y0, 0.25, 0.5))
legax.patch.set_visible(False)
legax.tick_params(
left=False, labelleft=False, bottom=False, labelbottom=False
)
legax.set_frame_on(False)
legax.set_aspect(1, anchor="SW")
legax.imshow(legend)
# hide the legend if the corresponding layer is not active at the moment
if self._layer not in self._m.BM._bg_layer.split("|"):
legax.set_visible(False)
self._m.BM.add_artist(legax, self._layer)
def cb_move(event):
if not self._legend_picked:
return
# only execute action if no toolbar action is active
if (
hasattr(self._m.f.canvas, "toolbar")
and self._m.f.canvas.toolbar is not None
and self._m.f.canvas.toolbar.mode != ""
):
return
if not event.button:
legax.set_frame_on(False)
return
bbox = Bbox.from_bounds(
event.x - legax.bbox.width / 2,
event.y - legax.bbox.height / 2,
legax.bbox.width,
legax.bbox.height,
)
bbox = bbox.transformed(self._m.f.transFigure.inverted())
legax.set_position(bbox)
self._m.BM.blit_artists([legax])
def cb_release(event):
self._legend_picked = False
legax.set_frame_on(False)
def cb_pick(event):
if event.inaxes == legax:
legax.set_frame_on(True)
self._legend_picked = True
else:
legax.set_frame_on(False)
self._legend_picked = False
def cb_keypress(event):
if not self._legend_picked:
return
if event.key in ["delete", "backspace"]:
self._m.BM.remove_artist(legax, self._layer)
legax.remove()
self._m.BM.update()
def cb_scroll(event):
if not self._legend_picked:
return
pos = legax.get_position()
steps = event.step
legax.set_position(
(
pos.x0,
pos.y0,
pos.width + steps * pos.width * 0.025,
pos.height + steps * pos.height * 0.025,
)
)
self._m.BM.blit_artists([legax])
self._m.f.canvas.mpl_connect("scroll_event", cb_scroll)
self._m.f.canvas.mpl_connect("button_press_event", cb_pick)
self._m.f.canvas.mpl_connect("button_release_event", cb_release)
self._m.f.canvas.mpl_connect("motion_notify_event", cb_move)
self._m.f.canvas.mpl_connect("key_press_event", cb_keypress)
self._m.parent._wms_legend.setdefault(self._layer, list()).append(legax)
self._m.BM.update()
return legax
def set_extent_to_bbox(self, shrink=False):
"""
Set the extent of the axis to the bounding-box of the WebMap service.
This is particularly useful for non-global WebMap services.
Shrinking the bbox can help to avoid HTTP-request errors for tiles outside
the bbox of the WebMap service.
Error-messages that might be solved by shrinking the extent before adding
the layer:
- `RuntimeError: You must first set the image array`
- `requests.exceptions.HTTPError: 404 Client Error: Not Found for url`
Parameters
----------
shrink : float, optional
Shrink the bounding-box by the provided shrinking factor (must be in [0, 1]).
- 0 : no shrinking (e.g. use the original bbox)
- < 1 : shrink the bbox by the factor (e.g. 0.5 = 50% smaller bbox)
The default is False.
Examples:
---------
>>> m = Maps()
>>> layer = m.add_wms.Austria.Wien_basemap.add_layer.lb
>>> layer.set_extent_to_bbox(shrink=0.5)
>>> layer()
"""
bbox = getattr(self.wms_layer, "boundingBox", None)
try:
(x0, y0, x1, y1, crs) = bbox
incrs = CRS.from_user_input(crs)
except Exception:
print(
"EOmaps: could not determine bbox from 'boundingBox'... "
+ "defaulting to 'boundingBoxWGS84'"
)
(x0, y0, x1, y1) = getattr(self.wms_layer, "boundingBoxWGS84", None)
incrs = CRS.from_user_input(4326)
if shrink:
assert shrink >= 0, "EOmaps: shrink must be > 0!"
assert shrink < 1, "EOmaps: shrink must be < 1!"
dx = abs(x1 - x0) / 2
dy = abs(y1 - y0) / 2
x0 += dx * shrink
x1 -= dx * shrink
y0 += dy * shrink
y1 -= dy * shrink
transformer = Transformer.from_crs(
incrs,
self._m.crs_plot,
always_xy=True,
)
(x0, x1), (y0, y1) = transformer.transform((x0, x1), (y0, y1))
self._m.ax.set_xlim(x0, x1)
self._m.ax.set_ylim(y0, y1)
def _set_style(self, style=None):
# style is a list with 1 entry!
styles = list(self.wms_layer.styles)
if style is not None:
assert (
style[0] in styles
), f"EOmaps: WebMap style {style} is not available, use one of {styles}"
self._style = style[0]
else:
style = [self._style]
return style
class _wmts_layer(_WebMap_layer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
pass
def __call__(self, layer=None, zorder=0, alpha=1, **kwargs):
"""
Add the WMTS layer to the map
Parameters
----------
layer : int, str or None, optional
The name of the layer at which map-features are plotted.
- If "all": the corresponding feature will be added to ALL layers
- If None, the layer of the parent object is used.
The default is None.
zorder : float
The zorder of the artist (e.g. the stacking level of overlapping artists)
The default is 0
alpha : float, optional
The alpha-transparency of the image.
NOTE: This changes the global transparency of the images... it does
not control whether the images are served with included transparency!
(check the "transparent" kwarg)
**kwargs :
additional kwargs passed to the WebMap service request.
(e.g. transparent=True, time='2020-02-05', etc.)
Additional Parameters
---------------------
transparent : bool, optional
Indicator if the WMS images should be read as RGB or RGBA
(e.g. with or without transparency). The default is False.
"""
from . import MapsGrid # do this here to avoid circular imports!
styles = self._set_style(kwargs.get("styles", None))
if styles is not None:
kwargs["styles"] = styles
for m in self._m if isinstance(self._m, MapsGrid) else [self._m]:
if layer is None:
self._layer = m.layer
else:
self._layer = layer
if self._layer == "all" or self._m.BM.bg_layer == self._layer:
# add the layer immediately if the layer is already active
self._do_add_layer(
self._m,
l=self._layer,
wms_kwargs=kwargs,
zorder=zorder,
alpha=alpha,
)
else:
# delay adding the layer until it is effectively activated
self._m.BM.on_layer(
func=partial(
self._do_add_layer,
wms_kwargs=kwargs,
zorder=zorder,
alpha=alpha,
),
layer=self._layer,
persistent=False,
m=m,
)
# ------------------------
# The following is very much a copy of "cartopy.mpl.geoaxes.GeoAxes.add_raster"
# and "cartopy.mpl.geoaxes.GeoAxes.add_wmts", using a different implementation
# for SlippyImageArtist
@staticmethod
def _add_wmts(ax, wms, layers, wms_kwargs=None, **kwargs):
from cartopy.io.ogc_clients import WMTSRasterSource
wms = WMTSRasterSource(wms, layers, gettile_extra_kwargs=wms_kwargs)
# Allow a fail-fast error if the raster source cannot provide
# images in the current projection.
wms.validate_projection(ax.projection)
img = SlippyImageArtist_NEW(ax, wms, **kwargs)
with ax.hold_limits():
ax.add_image(img)
return img
def _do_add_layer(self, m, l, **kwargs):
# actually add the layer to the map.
print(f"EOmaps: Adding wmts-layer: {self.name}")
# use slightly adapted implementation of cartopy's ax.add_wmts
art = self._add_wmts(
m.ax, self._wms, self.name, interpolation="spline36", **kwargs
)
m.BM.add_bg_artist(art, l)
class _wms_layer(_WebMap_layer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
pass
def __call__(self, layer=None, zorder=0, alpha=1, **kwargs):
"""
Add the WMS layer to the map
Parameters
----------
layer : int, str or None, optional
The name of the layer at which map-features are plotted.
- If "all": the corresponding feature will be added to ALL layers
- If None, the layer of the parent object is used.
The default is None.
zorder : float
The zorder of the artist (e.g. the stacking level of overlapping artists)
The default is 0
alpha : float, optional
The alpha-transparency of the image.
NOTE: This changes the global transparency of the images... it does
not control whether the images are served with included transparency!
(check the "transparent" kwarg)
**kwargs :
additional kwargs passed to the WebMap service request.
(e.g. transparent=True, time='2020-02-05', etc.)
Additional Parameters
---------------------
transparent : bool, optional
Indicator if the WMS images should be read as RGB or RGBA
(e.g. with or without transparency). The default is False.
"""
from . import MapsGrid # do this here to avoid circular imports!
styles = self._set_style(kwargs.get("styles", None))
if styles is not None:
kwargs["styles"] = styles
for m in self._m if isinstance(self._m, MapsGrid) else [self._m]:
if layer is None:
self._layer = m.layer
else:
self._layer = layer
if self._layer == "all" or m.BM.bg_layer == self._layer:
# add the layer immediately if the layer is already active
self._do_add_layer(
m=m,
l=self._layer,
wms_kwargs=kwargs,
zorder=zorder,
alpha=alpha,
)
else:
# delay adding the layer until it is effectively activated
m.BM.on_layer(
func=partial(
self._do_add_layer,
wms_kwargs=kwargs,
zorder=zorder,
alpha=alpha,
),
layer=self._layer,
persistent=False,
m=m,
)
# ------------------------
# The following is very much a copy of "cartopy.mpl.geoaxes.GeoAxes.add_raster"
# and "cartopy.mpl.geoaxes.GeoAxes.add_wms", using a different implementation
# for SlippyImageArtist
@staticmethod
def _add_wms(ax, wms, layers, wms_kwargs=None, **kwargs):
from cartopy.io.ogc_clients import WMSRasterSource
wms = WMSRasterSource(wms, layers, getmap_extra_kwargs=wms_kwargs)
# Allow a fail-fast error if the raster source cannot provide
# images in the current projection.
wms.validate_projection(ax.projection)
img = SlippyImageArtist_NEW(ax, wms, **kwargs)
with ax.hold_limits():
ax.add_image(img)
return img
def _do_add_layer(self, m, l, **kwargs):
# actually add the layer to the map.
print(f"EOmaps: ... adding wms-layer {self.name}")
# use slightly adapted implementation of cartopy's ax.add_wms
art = self._add_wms(
m.ax, self._wms, self.name, interpolation="spline36", **kwargs
)
m.BM.add_bg_artist(art, l)
class _WebServiec_collection(object):
def __init__(self, m, service_type="wmts", url=None):
self._m = m
self._service_type = service_type
if url is not None:
self._url = url
def __getitem__(self, key):
return self.add_layer.__dict__[key]
def __repr__(self):
if hasattr(self, "info"):
return self.info
else:
return object.__repr__(self)
@property
@lru_cache()
def layers(self):
"""
get a list of all available layers
"""
return list(self.add_layer.__dict__)
def findlayer(self, name):
"""
A convenience function to return any layer-name that contains the
provided "name"-string (the search is NOT case-sensitive!)
Parameters
----------
name : str
the string to search for in the layers.
Returns
-------
list
A list of all available layers that contain the provided string.
"""
return [i for i in self.layers if name.lower() in i.lower()]
@staticmethod
def _get_wmts(url):
# TODO expose useragent
return WebMapTileService(url)
@staticmethod
def _get_wms(url):
# TODO expose useragent
return WebMapService(url)
@property
@lru_cache()
def add_layer(self):
if self._service_type == "wmts":
wmts = self._get_wmts(self._url)
layers = dict()
for key in wmts.contents.keys():
layers[_sanitize(key)] = _wmts_layer(self._m, wmts, key)
elif self._service_type == "wms":
wms = self._get_wms(self._url)
layers = dict()
for key in wms.contents.keys():
layers[_sanitize(key)] = _wms_layer(self._m, wms, key)
return SimpleNamespace(**layers)
class REST_API_services:
def __init__(
self, m, url, name, service_type="wmts", layers=None, _params={"f": "pjson"}
):
"""
fetch layers from a Rest API
Parameters
----------
m : eomaps.Maps
the parent maps object.
url : str
the url to the API.
name : str
The name of the API.
service_type : str, optional
the service-type to use ("wms" or "wmts"). The default is "wmts".
layers : set, optional
A set of default layers used for delayed fetching (and autocompletion...)
As soon as one of the layers is accessed, the API is fetched and the
layers are updated according to the current status of the Server.
If None or empty, layers are immediately fetched!
The default is None.
_params : set, optional
additional parameters passed to the API. The default is {"f": "pjson"}.
"""
self._m = m
self._REST_url = url
self._name = name
self._service_type = service_type
self._params = _params
self._fetched = False
if layers is None:
layers = set()
self._layers = layers
for i in self._layers:
setattr(self, i, "NOT FOUND")
if len(self._layers) == 0:
self._fetch_services()
def __getattribute__(self, name):
# make sure all private properties are directly accessible
if name.startswith("_"):
return object.__getattribute__(self, name)
# fetch layers on first attempt to get a non-private attribute
if not self._fetched:
self._fetch_services()
return object.__getattribute__(self, name)
def _fetch_services(self):
if self._fetched:
return
# set _fetched to True immediately to avoid issues in __getattribute__
self._fetched = True
print(f"EOmaps: ... fetching services for '{self._name}'")
self._REST_API = _REST_API(self._REST_url, _params=self._params)
found_folders = set()
for foldername, services in self._REST_API._structure.items():
setattr(
self,
foldername,
_multi_REST_WMSservice(
m=self._m,
services=services,
service_type=self._service_type,
url=self._REST_url,
),
)
found_folders.add(foldername)
new_layers = found_folders - self._layers
if len(new_layers) > 0:
print(f"EOmaps: ... found some new folders: {new_layers}")
invalid_layers = self._layers - found_folders
if len(invalid_layers) > 0:
print(f"EOmaps: ... could not find the folders: {invalid_layers}")
for i in invalid_layers:
delattr(self, i)
print("EOmaps: done!")
class _REST_WMSservice(_WebServiec_collection):
def __init__(self, service, s_name, s_type, *args, **kwargs):
super().__init__(*args, **kwargs)
self._service = service
self._s_name = s_name
self._s_type = s_type
self._layers = None
@property
def _url(self):
print(self._s_name)
url = "/".join([self._service, self._s_name, self._s_type])
if self._service_type == "wms":
suffix = "/WMSServer?request=GetCapabilities&service=WMS"
WMSurl = url.replace("/rest/", "/") + suffix
if requests.get(WMSurl).status_code == 200:
url = WMSurl
else:
url = None
elif self._service_type == "wmts":
suffix = "/WMTS/1.0.0/WMTSCapabilities.xml"
WMSurl = url + suffix
if requests.get(WMSurl).status_code == 200:
url = WMSurl
else:
url = None
return url
def _fetch_layers(self):
self._layers = dict()
url = self._url
if url is not None:
if self._service_type == "wms":
wms = self._get_wms(url)
layer_names = list(wms.contents.keys())
for lname in layer_names:
self._layers["layer_" + _sanitize(lname)] = _wms_layer(
self._m, wms, lname
)
elif self._service_type == "wmts":
wmts = self._get_wmts(url)
layer_names = list(wmts.contents.keys())
for lname in layer_names:
self._layers["layer_" + _sanitize(lname)] = _wmts_layer(
self._m, wmts, lname
)
@property
@lru_cache()
def add_layer(self):
self._fetch_layers()
if len(self._layers) == 0:
print(f"EOmaps: found no {self._service_type} layers for {self._s_name}")
return
else:
return SimpleNamespace(**self._layers)
class _multi_REST_WMSservice:
def __init__(self, m, services, service_type, url, *args, **kwargs):
self._m = m
self._services = services
self._service_type = service_type
self._url = url
self._fetch_services()
@lru_cache()
def _fetch_services(self):
for (s_name, s_type) in self._services:
wms_layer = _REST_WMSservice(
m=self._m,
service=self._url,
s_name=s_name,
s_type=s_type,
service_type=self._service_type,
)
setattr(self, _sanitize(s_name), wms_layer)
class _REST_API(object):
# adapted from https://gis.stackexchange.com/a/113213
def __init__(self, url, _params={"f": "pjson"}):
self._url = url
self._params = _params
self._structure = self._get_structure(self._url)
def _post(self, service, _params={"f": "pjson"}, ret_json=True):
"""Post Request to REST Endpoint
Required:
service -- full path to REST endpoint of service
Optional:
_params -- parameters for posting a request
ret_json -- return the response as JSON. Default is True.
"""
r = requests.post(service, params=_params, verify=False)
# make sure return
if r.status_code != 200:
raise NameError(
'"{0}" service not found!\n{1}'.format(service, r.raise_for_status())
)
else:
if ret_json:
return r.json()
else:
return r
def _get_structure(self, service):
"""returns a list of all services
Optional:
service -- full path to a rest service
"""
with catch_warnings():
filterwarnings("ignore", category=InsecureRequestWarning)
all_services = dict()
r = self._post(service, _params=self._params)
# parse all services that are not inside a folder
for s in r["services"]:
all_services.setdefault("SERVICES", []).append((s["name"], s["type"]))
for s in r["folders"]:
new = "/".join([service, s])
endpt = self._post(new, _params=self._params)
for serv in endpt["services"]:
if str(serv["type"]) == "MapServer":
all_services.setdefault(s, []).append(
(serv["name"], serv["type"])
)
return all_services
class TileFactory(GoogleWTS):
def __init__(self, url, *args, **kwargs):
super().__init__(*args, **kwargs)
self._url = url
def _image_url(self, tile):
x, y, z = tile
if isinstance(self._url, str):
return self._url.format(x=x, y=y, z=z)
if callable(self._url):
return self._url(x=x, y=y, z=z)
class xyzRasterSource(RasterSource):
"""
A RasterSource that can be used with a SlippyImageArtist to fetch tiles.
"""
def __init__(self, url, crs, maxzoom=19, transparent=True):
"""
Parameters
----------
service: string or WebMapService instance
The WebMapService instance, or URL of a WMS service,
from whence to retrieve the image.
layers: string or list of strings
The name(s) of layers to use from the WMS service.
"""
self.url = url
self._crs = crs
self._maxzoom = maxzoom
if transparent is True:
self.desired_tile_form = "RGBA"
else:
self.desired_tile_form = "RGB"
self._factory = TileFactory(self.url, desired_tile_form=self.desired_tile_form)
# function to estimate a proper zoom-level
@staticmethod
def _getz(d, zmax):
z = int(np.clip(np.ceil(np.log2(1 / d * 40075016.68557849)), 0, zmax))
return z
def getz(self, extent, target_resolution, zmax):
import shapely.geometry as sgeom
x0, x1, y0, y1 = extent
d = x1 - x0
domain = sgeom.box(x0, y0, x1, y1)
z = self._getz(d, zmax)
ntiles = len(list(self._factory.find_images(domain, z)))
# use the target resolution to increase the zoom-level until we use a
# reasonable amount of tiles
nimgs = np.ceil(max(target_resolution) / 256) ** 2
while ntiles < nimgs:
if z >= self._maxzoom:
break
z += 1
ntiles = len(list(self._factory.find_images(domain, z)))
return min(z, self._maxzoom)
def _native_srs(self, projection):
# Return the SRS which corresponds to the given projection when
# known, otherwise return None.
return self._crs
def validate_projection(self, projection):
# no need to validate the projection, we're always in 3857
pass
def _image_and_extent(
self,
wms_proj,
wms_srs,
wms_extent,
output_proj,
output_extent,
target_resolution,
):
import shapely.geometry as sgeom
x0, x1, y0, y1 = wms_extent
domain = sgeom.box(x0, y0, x1, y1)
img, extent, origin = self._factory.image_for_domain(
domain,
self.getz(wms_extent, target_resolution, self._maxzoom),
)
# import PIL.Image
# output_extent = _target_extents(extent, self._crs, output_proj)[0]
# return _warped_located_image(PIL.Image.fromarray(img), wms_srs, extent,
# output_proj,
# output_extent,
# target_resolution
# )
# ------------- ---------------------------------------------------------------
# ------------- the following is copied from cartopy's version of ax.imshow
# ------------- since the above lines don't work for some reason...
if output_proj == wms_srs:
pass
else:
img = np.asanyarray(img)
if origin == "upper":
# It is implicitly assumed by the regridding operation that the
# origin of the image is 'lower', so simply adjust for that
# here.
img = img[::-1]
# reproject the extent to the output-crs
target_extent = ogc_clients._target_extents(extent, self._crs, output_proj)
if len(target_extent) > 0:
target_extent = target_extent[0]
else:
# TODO properly check what's going on here
# (only relevant for Equi7Grid projections if a xyz-layer is added
# without zooming first)
target_extent = output_extent
regrid_shape = [int(i * 2) for i in target_resolution]
# check self._m.ax._regrid_shape_aspect for a more proper regrid_shape
# Lazy import because scipy/pykdtree in img_transform are only
# optional dependencies
from cartopy.img_transform import warp_array
original_extent = extent
img, extent = warp_array(
img,
source_proj=self._crs,
source_extent=original_extent,
target_proj=output_proj,
target_res=regrid_shape,
target_extent=target_extent,
mask_extrapolated=True,
)
if origin == "upper":
# revert to the initial origin
img = img[::-1]
from cartopy.io.ogc_clients import LocatedImage
return LocatedImage(img, extent)
def fetch_raster(self, projection, extent, target_resolution):
target_resolution = [np.ceil(val) for val in target_resolution]
if projection == self._crs:
wms_extents = [extent]
else:
# Calculate the bounding box(es) in WMS projection.
wms_extents = _target_extents(extent, projection, self._crs)
located_images = []
for wms_extent in wms_extents:
img = self._image_and_extent(
self._crs,