-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
raster_layers.py
425 lines (380 loc) · 14.8 KB
/
raster_layers.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
"""
Wraps leaflet TileLayer, WmsTileLayer (TileLayer.WMS), ImageOverlay, and VideoOverlay
"""
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
from branca.element import Element, Figure
from jinja2 import Environment, PackageLoader, Template
from folium.map import Layer
from folium.utilities import (
TypeBounds,
TypeJsonValue,
image_to_url,
mercator_transform,
parse_options,
)
if TYPE_CHECKING:
import xyzservices
ENV = Environment(loader=PackageLoader("folium", "templates"))
class TileLayer(Layer):
"""
Create a tile layer to append on a Map.
Parameters
----------
tiles: str or :class:`xyzservices.TileProvider`, default 'OpenStreetMap'
Map tileset to use. Can choose from this list of built-in tiles:
- "OpenStreetMap"
- "Stamen Terrain", "Stamen Toner", "Stamen Watercolor"
- "CartoDB positron", "CartoDB dark_matter"
You can pass a custom tileset to Folium by passing a
:class:`xyzservices.TileProvider` or a Leaflet-style
URL to the tiles parameter: ``http://{s}.yourtiles.com/{z}/{x}/{y}.png``.
You can find a list of free tile providers here:
``http://leaflet-extras.github.io/leaflet-providers/preview/``.
Be sure to check their terms and conditions and to provide attribution
with the `attr` keyword.
min_zoom: int, default 0
Minimum allowed zoom level for this tile layer.
max_zoom: int, default 18
Maximum allowed zoom level for this tile layer.
max_native_zoom: int, default None
The highest zoom level at which the tile server can provide tiles.
If provided you can zoom in past this level. Else tiles will turn grey.
attr: string, default None
Map tile attribution; only required if passing custom tile URL.
detect_retina: bool, default False
If true and user is on a retina display, it will request four
tiles of half the specified size and a bigger zoom level in place
of one to utilize the high resolution.
name : string, default None
The name of the Layer, as it will appear in LayerControls
overlay : bool, default False
Adds the layer as an optional overlay (True) or the base layer (False).
control : bool, default True
Whether the Layer will be included in LayerControls.
show: bool, default True
Whether the layer will be shown on opening (only for overlays).
subdomains: list of strings, default ['abc']
Subdomains of the tile service.
tms: bool, default False
If true, inverses Y axis numbering for tiles (turn this on for TMS
services).
opacity: float, default 1
Sets the opacity for the layer.
**kwargs : additional keyword arguments
Other keyword arguments are passed as options to the Leaflet tileLayer
object.
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.tileLayer(
{{ this.tiles|tojson }},
{{ this.options|tojson }}
).addTo({{ this._parent.get_name() }});
{% endmacro %}
"""
)
def __init__(
self,
tiles: Union[str, "xyzservices.TileProvider"] = "OpenStreetMap",
min_zoom: int = 0,
max_zoom: int = 18,
max_native_zoom: Optional[int] = None,
attr: Optional[str] = None,
detect_retina: bool = False,
name: Optional[str] = None,
overlay: bool = False,
control: bool = True,
show: bool = True,
no_wrap: bool = False,
subdomains: str = "abc",
tms: bool = False,
opacity: float = 1,
**kwargs
):
# check for xyzservices.TileProvider without importing it
if isinstance(tiles, dict):
attr = attr if attr else tiles.html_attribution # type: ignore
min_zoom = tiles.get("min_zoom", min_zoom)
max_zoom = tiles.get("max_zoom", max_zoom)
subdomains = tiles.get("subdomains", subdomains)
tiles = tiles.build_url(fill_subdomain=False, scale_factor="{r}") # type: ignore
self.tile_name = (
name if name is not None else "".join(tiles.lower().strip().split())
)
super().__init__(
name=self.tile_name, overlay=overlay, control=control, show=show
)
self._name = "TileLayer"
self._env = ENV
tiles_flat = "".join(tiles.lower().strip().split())
if tiles_flat in {"cloudmade", "mapbox", "mapboxbright", "mapboxcontrolroom"}:
# added in May 2020 after v0.11.0, remove in a future release
raise ValueError(
"Built-in templates for Mapbox and Cloudmade have been removed. "
"You can still use these providers by passing a URL to the `tiles` "
"argument. See the documentation of the `TileLayer` class."
)
templates = list(
self._env.list_templates(filter_func=lambda x: x.startswith("tiles/"))
)
tile_template = "tiles/" + tiles_flat + "/tiles.txt"
attr_template = "tiles/" + tiles_flat + "/attr.txt"
if tile_template in templates and attr_template in templates:
self.tiles = self._env.get_template(tile_template).render()
attr = self._env.get_template(attr_template).render()
else:
self.tiles = tiles
if not attr:
raise ValueError("Custom tiles must have an attribution.")
self.options = parse_options(
min_zoom=min_zoom,
max_zoom=max_zoom,
max_native_zoom=max_native_zoom or max_zoom,
no_wrap=no_wrap,
attribution=attr,
subdomains=subdomains,
detect_retina=detect_retina,
tms=tms,
opacity=opacity,
**kwargs
)
class WmsTileLayer(Layer):
"""
Creates a Web Map Service (WMS) layer.
Parameters
----------
url : str
The url of the WMS server.
layers : str
Comma-separated list of WMS layers to show.
styles : str, optional
Comma-separated list of WMS styles.
fmt : str, default 'image/jpeg'
The format of the service output. Ex: 'image/png'
transparent: bool, default False
Whether the layer shall allow transparency.
version : str, default '1.1.1'
Version of the WMS service to use.
attr : str, default ''
The attribution of the service.
Will be displayed in the bottom right corner.
name : string, optional
The name of the Layer, as it will appear in LayerControls
overlay : bool, default True
Adds the layer as an optional overlay (True) or the base layer (False).
control : bool, default True
Whether the Layer will be included in LayerControls.
show: bool, default True
Whether the layer will be shown on opening (only for overlays).
**kwargs : additional keyword arguments
Passed through to the underlying tileLayer.wms object and can be used
for setting extra tileLayer.wms parameters or as extra parameters in
the WMS request.
See https://leafletjs.com/reference.html#tilelayer-wms
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.tileLayer.wms(
{{ this.url|tojson }},
{{ this.options|tojson }}
).addTo({{ this._parent.get_name() }});
{% endmacro %}
"""
) # noqa
def __init__(
self,
url: str,
layers: str,
styles: str = "",
fmt: str = "image/jpeg",
transparent: bool = False,
version: str = "1.1.1",
attr: str = "",
name: Optional[str] = None,
overlay: bool = True,
control: bool = True,
show: bool = True,
**kwargs
):
super().__init__(name=name, overlay=overlay, control=control, show=show)
self.url = url
kwargs["format"] = fmt
cql_filter = kwargs.pop("cql_filter", None)
self.options = parse_options(
layers=layers,
styles=styles,
transparent=transparent,
version=version,
attribution=attr,
**kwargs
)
if cql_filter:
# special parameter that shouldn't be camelized
self.options["cql_filter"] = cql_filter
class ImageOverlay(Layer):
"""
Used to load and display a single image over specific bounds of
the map, implements ILayer interface.
Parameters
----------
image: string, file or array-like object
The data you want to draw on the map.
* If string, it will be written directly in the output file.
* If file, it's content will be converted as embedded in the output file.
* If array-like, it will be converted to PNG base64 string and embedded in the output.
bounds: list
Image bounds on the map in the form
[[lat_min, lon_min], [lat_max, lon_max]]
opacity: float, default Leaflet's default (1.0)
alt: string, default Leaflet's default ('')
origin: ['upper' | 'lower'], optional, default 'upper'
Place the [0,0] index of the array in the upper left or
lower left corner of the axes.
colormap: callable, used only for `mono` image.
Function of the form [x -> (r,g,b)] or [x -> (r,g,b,a)]
for transforming a mono image into RGB.
It must output iterables of length 3 or 4,
with values between 0 and 1.
Hint: you can use colormaps from `matplotlib.cm`.
mercator_project: bool, default False.
Used only for array-like image. Transforms the data to
project (longitude, latitude) coordinates to the Mercator projection.
Beware that this will only work if `image` is an array-like object.
Note that if used the image will be clipped beyond latitude -85 and 85.
pixelated: bool, default True
Sharp sharp/crips (True) or aliased corners (False).
name : string, default None
The name of the Layer, as it will appear in LayerControls
overlay : bool, default True
Adds the layer as an optional overlay (True) or the base layer (False).
control : bool, default True
Whether the Layer will be included in LayerControls.
show: bool, default True
Whether the layer will be shown on opening (only for overlays).
See https://leafletjs.com/reference.html#imageoverlay for more
options.
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.imageOverlay(
{{ this.url|tojson }},
{{ this.bounds|tojson }},
{{ this.options|tojson }}
).addTo({{ this._parent.get_name() }});
{% endmacro %}
"""
)
def __init__(
self,
image: Any,
bounds: TypeBounds,
origin: str = "upper",
colormap: Optional[Callable] = None,
mercator_project: bool = False,
pixelated: bool = True,
name: Optional[str] = None,
overlay: bool = True,
control: bool = True,
show: bool = True,
**kwargs
):
super().__init__(name=name, overlay=overlay, control=control, show=show)
self._name = "ImageOverlay"
self.bounds = bounds
self.options = parse_options(**kwargs)
self.pixelated = pixelated
if mercator_project:
image = mercator_transform(
image, (bounds[0][0], bounds[1][0]), origin=origin
)
self.url = image_to_url(image, origin=origin, colormap=colormap)
def render(self, **kwargs) -> None:
super().render()
figure = self.get_root()
assert isinstance(
figure, Figure
), "You cannot render this Element if it is not in a Figure."
if self.pixelated:
pixelated = """
<style>
.leaflet-image-layer {
/* old android/safari*/
image-rendering: -webkit-optimize-contrast;
image-rendering: crisp-edges; /* safari */
image-rendering: pixelated; /* chrome */
image-rendering: -moz-crisp-edges; /* firefox */
image-rendering: -o-crisp-edges; /* opera */
-ms-interpolation-mode: nearest-neighbor; /* ie */
}
</style>
"""
figure.header.add_child(
Element(pixelated), name="leaflet-image-layer"
) # noqa
def _get_self_bounds(self) -> TypeBounds:
"""
Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]].
"""
return self.bounds
class VideoOverlay(Layer):
"""
Used to load and display a video over the map.
Parameters
----------
video_url: str
URL of the video
bounds: list
Video bounds on the map in the form
[[lat_min, lon_min], [lat_max, lon_max]]
autoplay: bool, default True
loop: bool, default True
name : string, default None
The name of the Layer, as it will appear in LayerControls
overlay : bool, default True
Adds the layer as an optional overlay (True) or the base layer (False).
control : bool, default True
Whether the Layer will be included in LayerControls.
show: bool, default True
Whether the layer will be shown on opening (only for overlays).
**kwargs:
Other valid (possibly inherited) options. See:
https://leafletjs.com/reference.html#videooverlay
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
var {{ this.get_name() }} = L.videoOverlay(
{{ this.video_url|tojson }},
{{ this.bounds|tojson }},
{{ this.options|tojson }}
).addTo({{ this._parent.get_name() }});
{% endmacro %}
"""
)
def __init__(
self,
video_url: str,
bounds: TypeBounds,
autoplay: bool = True,
loop: bool = True,
name: Optional[str] = None,
overlay: bool = True,
control: bool = True,
show: bool = True,
**kwargs: TypeJsonValue
):
super().__init__(name=name, overlay=overlay, control=control, show=show)
self._name = "VideoOverlay"
self.video_url = video_url
self.bounds = bounds
self.options = parse_options(autoplay=autoplay, loop=loop, **kwargs)
def _get_self_bounds(self) -> TypeBounds:
"""
Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]]
"""
return self.bounds