/
foliumap.py
3175 lines (2735 loc) · 125 KB
/
foliumap.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
"""Module for creating interactive maps with the folium library."""
# *******************************************************************************#
# This module contains extra features of the geemap package. #
# The geemap community will maintain the extra features. #
# *******************************************************************************#
import os
import ee
import folium
from box import Box
from folium import plugins
from branca.element import Figure, JavascriptLink, MacroElement
from folium.elements import JSCSSMixin
from folium.map import Layer
from jinja2 import Template
from .basemaps import xyz_to_folium
from .common import *
from .conversion import *
from .ee_tile_layers import *
from .legends import builtin_legends
from .osm import *
from .timelapse import *
from .plot import *
from . import examples
if not in_colab_shell():
from .plot import *
basemaps = Box(xyz_to_folium(), frozen_box=True)
class Map(folium.Map):
"""The Map class inherits from folium.Map. By default, the Map will add Google Maps as the basemap. Set add_google_map = False to use OpenStreetMap as the basemap.
Returns:
object: folium map object.
"""
def __init__(self, **kwargs):
import logging
logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)
if "ee_initialize" not in kwargs.keys():
kwargs["ee_initialize"] = True
if kwargs["ee_initialize"]:
ee_initialize()
# Default map center location and zoom level
latlon = [20, 0]
zoom = 2
# Interchangeable parameters between ipyleaflet and folium
if "center" in kwargs.keys():
kwargs["location"] = kwargs["center"]
kwargs.pop("center")
if "location" in kwargs.keys():
latlon = kwargs["location"]
else:
kwargs["location"] = latlon
if "zoom" in kwargs.keys():
kwargs["zoom_start"] = kwargs["zoom"]
kwargs.pop("zoom")
if "zoom_start" in kwargs.keys():
zoom = kwargs["zoom_start"]
else:
kwargs["zoom_start"] = zoom
if "max_zoom" not in kwargs.keys():
kwargs["max_zoom"] = 30
if "add_google_map" not in kwargs.keys() and "basemap" not in kwargs.keys():
kwargs["add_google_map"] = False
if "plugin_LatLngPopup" not in kwargs.keys():
kwargs["plugin_LatLngPopup"] = False
if "plugin_Fullscreen" not in kwargs.keys():
kwargs["plugin_Fullscreen"] = True
if "plugin_Draw" not in kwargs.keys():
kwargs["plugin_Draw"] = True
if "Draw_export" not in kwargs.keys():
kwargs["Draw_export"] = False
if "plugin_MiniMap" not in kwargs.keys():
kwargs["plugin_MiniMap"] = False
# if "plugin_LayerControl" not in kwargs.keys():
# kwargs["plugin_LayerControl"] = False
if "locate_control" not in kwargs:
kwargs["locate_control"] = False
if "search_control" not in kwargs:
kwargs["search_control"] = True
if "scale_control" in kwargs:
kwargs["scale"] = kwargs["scale_control"]
kwargs.pop("scale_control")
if (
"width" in kwargs
and isinstance(kwargs["width"], str)
and ("%" not in kwargs["width"])
):
kwargs["width"] = float(kwargs["width"].replace("px", ""))
height = None
width = None
if "height" in kwargs:
height = kwargs.pop("height")
else:
height = 600
if "width" in kwargs:
width = kwargs.pop("width")
else:
width = "100%"
super().__init__(**kwargs)
self.baseclass = "folium"
# The list of Earth Engine Geometry objects converted from geojson
self.draw_features = []
# The Earth Engine Geometry object converted from the last drawn feature
self.draw_last_feature = None
self.draw_layer = None
self.user_roi = None
self.user_rois = None
self.search_locations = None
self.search_loc_marker = None
self.search_loc_geom = None
if (height is not None) or (width is not None):
f = folium.Figure(width=width, height=height)
self.add_to(f)
if kwargs.get("add_google_map"):
basemaps["ROADMAP"].add_to(self)
if kwargs.get("basemap"):
basemaps[kwargs.get("basemap")].add_to(self)
if kwargs.get("plugin_LatLngPopup"):
folium.LatLngPopup().add_to(self)
if kwargs.get("plugin_Fullscreen"):
plugins.Fullscreen().add_to(self)
if kwargs.get("plugin_Draw"):
plugins.Draw(export=kwargs.get("Draw_export")).add_to(self)
if kwargs.get("plugin_MiniMap"):
plugins.MiniMap().add_to(self)
if kwargs.get("plugin_LayerControl"):
folium.LayerControl().add_to(self)
if kwargs["locate_control"]:
plugins.LocateControl().add_to(self)
if kwargs["search_control"]:
plugins.Geocoder(collapsed=True, position="topleft").add_to(self)
if "plugin_LayerControl" not in kwargs:
self.options["layersControl"] = True
else:
self.options["layersControl"] = kwargs["plugin_LayerControl"]
self.fit_bounds([latlon, latlon], max_zoom=zoom)
def setOptions(self, mapTypeId="HYBRID", styles={}, types=[]):
"""Adds Google basemap to the map.
Args:
mapTypeId (str, optional): A mapTypeId to set the basemap to. Can be one of "ROADMAP", "SATELLITE", "HYBRID" or "TERRAIN" to select one of the standard Google Maps API map types. Defaults to 'HYBRID'.
styles ([type], optional): A dictionary of custom MapTypeStyle objects keyed with a name that will appear in the map's Map Type Controls. Defaults to None.
types ([type], optional): A list of mapTypeIds to make available. If omitted, but opt_styles is specified, appends all of the style keys to the standard Google Maps API map types.. Defaults to None.
"""
try:
basemaps[mapTypeId].add_to(self)
except Exception:
raise Exception(
"Basemap can only be one of the following: {}".format(
", ".join(basemaps.keys())
)
)
set_options = setOptions
def add_basemap(self, basemap="ROADMAP", **kwargs):
"""Adds a basemap to the map.
Args:
basemap (str, optional): Can be one of string from ee_basemaps. Defaults to 'ROADMAP'.
"""
try:
map_dict = {
"ROADMAP": "Esri.WorldStreetMap",
"SATELLITE": "Esri.WorldImagery",
"TERRAIN": "Esri.WorldTopoMap",
"HYBRID": "Esri.WorldImagery",
}
if isinstance(basemap, str):
if basemap.upper() in map_dict:
if basemap in os.environ:
if "name" in kwargs:
kwargs["name"] = basemap
basemap = os.environ[basemap]
self.add_tile_layer(tiles=basemap, **kwargs)
else:
basemap = basemap.upper()
basemaps[basemap].add_to(self)
except Exception:
raise Exception(
"Basemap can only be one of the following: {}".format(
", ".join(basemaps.keys())
)
)
def add_layer(
self,
ee_object,
vis_params={},
name="Layer untitled",
shown=True,
opacity=1.0,
**kwargs,
):
"""Adds a given EE object to the map as a layer.
Args:
ee_object (Collection|Feature|Image|MapId): The object to add to the map.
vis_params (dict, optional): The visualization parameters. Defaults to {}.
name (str, optional): The name of the layer. Defaults to 'Layer untitled'.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
"""
layer = EEFoliumTileLayer(ee_object, vis_params, name, shown, opacity, **kwargs)
layer.add_to(self)
arc_add_layer(layer.url_format, name, shown, opacity)
addLayer = add_layer
def _repr_mimebundle_(self, **kwargs):
"""Adds Layer control to the map. Reference: https://ipython.readthedocs.io/en/stable/config/integrating.html#MyObject._repr_mimebundle_"""
if self.options["layersControl"]:
self.add_layer_control()
def set_center(self, lon, lat, zoom=10):
"""Centers the map view at a given coordinates with the given zoom level.
Args:
lon (float): The longitude of the center, in degrees.
lat (float): The latitude of the center, in degrees.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to 10.
"""
self.fit_bounds([[lat, lon], [lat, lon]], max_zoom=zoom)
if is_arcpy():
arc_zoom_to_extent(lon, lat, lon, lat)
setCenter = set_center
def zoom_to_bounds(self, bounds):
"""Zooms to a bounding box in the form of [minx, miny, maxx, maxy].
Args:
bounds (list | tuple): A list/tuple containing minx, miny, maxx, maxy values for the bounds.
"""
# The folium fit_bounds method takes lat/lon bounds in the form [[south, west], [north, east]].
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def zoom_to_gdf(self, gdf):
"""Zooms to the bounding box of a GeoPandas GeoDataFrame.
Args:
gdf (GeoDataFrame): A GeoPandas GeoDataFrame.
"""
bounds = gdf.total_bounds
self.zoom_to_bounds(bounds)
def center_object(self, ee_object, zoom=None):
"""Centers the map view on a given object.
Args:
ee_object (Element|Geometry): An Earth Engine object to center on a geometry, image or feature.
zoom (int, optional): The zoom level, from 1 to 24. Defaults to None.
"""
maxError = 0.001
if isinstance(ee_object, ee.Geometry):
geometry = ee_object.transform(maxError=maxError)
else:
try:
geometry = ee_object.geometry(maxError=maxError).transform(
maxError=maxError
)
except Exception:
raise Exception(
"ee_object must be an instance of one of ee.Geometry, ee.FeatureCollection, ee.Image, or ee.ImageCollection."
)
if zoom is not None:
if not isinstance(zoom, int):
raise Exception("Zoom must be an integer.")
else:
centroid = geometry.centroid(maxError=maxError).getInfo()["coordinates"]
lat = centroid[1]
lon = centroid[0]
self.set_center(lon, lat, zoom)
if is_arcpy():
arc_zoom_to_extent(lon, lat, lon, lat)
else:
coordinates = geometry.bounds(maxError).getInfo()["coordinates"][0]
x = [c[0] for c in coordinates]
y = [c[1] for c in coordinates]
xmin = min(x)
xmax = max(x)
ymin = min(y)
ymax = max(y)
bounds = [[ymin, xmin], [ymax, xmax]]
self.fit_bounds(bounds)
if is_arcpy():
arc_zoom_to_extent(xmin, ymin, xmax, ymax)
centerObject = center_object
def set_control_visibility(
self, layerControl=True, fullscreenControl=True, latLngPopup=True
):
"""Sets the visibility of the controls on the map.
Args:
layerControl (bool, optional): Whether to show the control that allows the user to toggle layers on/off. Defaults to True.
fullscreenControl (bool, optional): Whether to show the control that allows the user to make the map full-screen. Defaults to True.
latLngPopup (bool, optional): Whether to show the control that pops up the Lat/lon when the user clicks on the map. Defaults to True.
"""
if layerControl:
folium.LayerControl().add_to(self)
if fullscreenControl:
plugins.Fullscreen().add_to(self)
if latLngPopup:
folium.LatLngPopup().add_to(self)
setControlVisibility = set_control_visibility
def add_layer_control(self):
"""Adds layer control to the map."""
layer_ctrl = False
for item in self.to_dict()["children"]:
if item.startswith("layer_control"):
layer_ctrl = True
break
if not layer_ctrl:
folium.LayerControl().add_to(self)
addLayerControl = add_layer_control
def add_marker(
self, location, popup=None, tooltip=None, icon=None, draggable=False, **kwargs
):
"""Adds a marker to the map. More info about marker options at https://python-visualization.github.io/folium/modules.html#folium.map.Marker.
Args:
location (list | tuple): The location of the marker in the format of [lat, lng].
popup (str, optional): The popup text. Defaults to None.
tooltip (str, optional): The tooltip text. Defaults to None.
icon (str, optional): The icon to use. Defaults to None.
draggable (bool, optional): Whether the marker is draggable. Defaults to False.
"""
if isinstance(location, list):
location = tuple(location)
if isinstance(location, tuple):
folium.Marker(
location=location,
popup=popup,
tooltip=tooltip,
icon=icon,
draggable=draggable,
**kwargs,
).add_to(self)
else:
raise TypeError("The location must be a list or a tuple.")
def add_wms_layer(
self,
url,
layers,
name=None,
attribution="",
overlay=True,
control=True,
shown=True,
format="image/png",
transparent=True,
version="1.1.1",
styles="",
**kwargs,
):
"""Add a WMS layer to the map.
Args:
url (str): The URL of the WMS web service.
layers (str): Comma-separated list of WMS layers to show.
name (str, optional): The layer name to use on the layer control. Defaults to None.
attribution (str, optional): The attribution of the data layer. Defaults to ''.
overlay (str, optional): Allows overlay. Defaults to True.
control (str, optional): Adds the layer to the layer control. Defaults to True.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
format (str, optional): WMS image format (use ‘image/png’ for layers with transparency). Defaults to 'image/png'.
transparent (bool, optional): Whether the layer shall allow transparency. Defaults to True.
version (str, optional): Version of the WMS service to use. Defaults to "1.1.1".
styles (str, optional): Comma-separated list of WMS styles. Defaults to "".
"""
try:
folium.raster_layers.WmsTileLayer(
url=url,
layers=layers,
name=name,
attr=attribution,
overlay=overlay,
control=control,
show=shown,
styles=styles,
fmt=format,
transparent=transparent,
version=version,
**kwargs,
).add_to(self)
except Exception:
raise Exception("Failed to add the specified WMS TileLayer.")
def add_tile_layer(
self,
tiles="OpenStreetMap",
name="Untitled",
attribution=".",
overlay=True,
control=True,
shown=True,
opacity=1.0,
API_key=None,
**kwargs,
):
"""Add a XYZ tile layer to the map.
Args:
tiles (str): The URL of the XYZ tile service.
name (str, optional): The layer name to use on the layer control. Defaults to 'Untitled'.
attribution (str, optional): The attribution of the data layer. Defaults to '.'.
overlay (str, optional): Allows overlay. Defaults to True.
control (str, optional): Adds the layer to the layer control. Defaults to True.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
opacity (float, optional): Sets the opacity for the layer.
API_key (str, optional): – API key for Cloudmade or Mapbox tiles. Defaults to True.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
folium.raster_layers.TileLayer(
tiles=tiles,
name=name,
attr=attribution,
overlay=overlay,
control=control,
show=shown,
opacity=opacity,
API_key=API_key,
**kwargs,
).add_to(self)
except Exception:
raise Exception("Failed to add the specified TileLayer.")
def add_cog_layer(
self,
url,
name="Untitled",
attribution=".",
opacity=1.0,
shown=True,
bands=None,
titiler_endpoint=None,
**kwargs,
):
"""Adds a COG TileLayer to the map.
Args:
url (str): The URL of the COG tile layer.
name (str, optional): The layer name to use for the layer. Defaults to 'Untitled'.
attribution (str, optional): The attribution to use. Defaults to '.'.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
bands (list, optional): A list of bands to use. Defaults to None.
titiler_endpoint (str, optional): Titiler endpoint. Defaults to "https://titiler.xyz".
"""
tile_url = cog_tile(url, bands, titiler_endpoint, **kwargs)
bounds = cog_bounds(url, titiler_endpoint)
self.add_tile_layer(
tiles=tile_url,
name=name,
attribution=attribution,
opacity=opacity,
shown=shown,
)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def add_cog_mosaic(self, **kwargs):
raise NotImplementedError(
"This function is no longer supported.See https://github.com/giswqs/leafmap/issues/180."
)
def add_stac_layer(
self,
url=None,
collection=None,
item=None,
assets=None,
bands=None,
titiler_endpoint=None,
name="STAC Layer",
attribution=".",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a STAC TileLayer to the map.
Args:
url (str): HTTP URL to a STAC item, e.g., https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json
collection (str): The Microsoft Planetary Computer STAC collection ID, e.g., landsat-8-c2-l2.
item (str): The Microsoft Planetary Computer STAC item ID, e.g., LC08_L2SP_047027_20201204_02_T1.
assets (str | list): The Microsoft Planetary Computer STAC asset ID, e.g., ["SR_B7", "SR_B5", "SR_B4"].
bands (list): A list of band names, e.g., ["SR_B7", "SR_B5", "SR_B4"]
titiler_endpoint (str, optional): Titiler endpoint, e.g., "https://titiler.xyz", "planetary-computer", "pc". Defaults to None.
name (str, optional): The layer name to use for the layer. Defaults to 'STAC Layer'.
attribution (str, optional): The attribution to use. Defaults to ''.
opacity (float, optional): The opacity of the layer. Defaults to 1.
shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
"""
tile_url = stac_tile(
url, collection, item, assets, bands, titiler_endpoint, **kwargs
)
bounds = stac_bounds(url, collection, item, titiler_endpoint)
self.add_tile_layer(
url=tile_url,
name=name,
attribution=attribution,
opacity=opacity,
shown=shown,
)
self.fit_bounds([[bounds[1], bounds[0]], [bounds[3], bounds[2]]])
def add_raster(
self,
source: str,
indexes: Optional[int] = None,
colormap: Optional[str] = None,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
nodata: Optional[float] = None,
attribution: Optional[str] = None,
layer_name: Optional[str] = "Raster",
array_args: Optional[Dict] = {},
**kwargs,
):
"""Add a local raster dataset to the map.
If you are using this function in JupyterHub on a remote server (e.g., Binder, Microsoft Planetary Computer) and
if the raster does not render properly, try installing jupyter-server-proxy using `pip install jupyter-server-proxy`,
then running the following code before calling this function. For more info, see https://bit.ly/3JbmF93.
import os
os.environ['LOCALTILESERVER_CLIENT_PREFIX'] = 'proxy/{port}'
Args:
source (str): The path to the GeoTIFF file or the URL of the Cloud Optimized GeoTIFF.
indexes (int, optional): The band(s) to use. Band indexing starts at 1. Defaults to None.
colormap (str, optional): The name of the colormap from `matplotlib` to use when plotting a single band. See https://matplotlib.org/stable/gallery/color/colormap_reference.html. Default is greyscale.
vmin (float, optional): The minimum value to use when colormapping the colormap when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the colormap when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to 'Raster'.
array_args (dict, optional): Additional arguments to pass to `array_to_image`. Defaults to {}.
"""
import numpy as np
import xarray as xr
if isinstance(source, np.ndarray) or isinstance(source, xr.DataArray):
source = array_to_image(source, **array_args)
tile_layer, tile_client = get_local_tile_layer(
source,
indexes=indexes,
colormap=colormap,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
tile_format="folium",
layer_name=layer_name,
return_client=True,
**kwargs,
)
tile_layer.add_to(self)
bounds = tile_client.bounds() # [ymin, ymax, xmin, xmax]
bounds = (
bounds[2],
bounds[0],
bounds[3],
bounds[1],
) # [minx, miny, maxx, maxy]
self.zoom_to_bounds(bounds)
arc_add_layer(tile_layer.tiles, layer_name, True, 1.0)
arc_zoom_to_extent(bounds[0], bounds[1], bounds[2], bounds[3])
def add_remote_tile(
self,
source,
band=None,
palette=None,
vmin=None,
vmax=None,
nodata=None,
attribution=None,
layer_name=None,
**kwargs,
):
"""Add a remote Cloud Optimized GeoTIFF (COG) to the map.
Args:
source (str): The path to the remote Cloud Optimized GeoTIFF.
band (int, optional): The band to use. Band indexing starts at 1. Defaults to None.
palette (str, optional): The name of the color palette from `palettable` to use when plotting a single band. See https://jiffyclub.github.io/palettable. Default is greyscale
vmin (float, optional): The minimum value to use when colormapping the palette when plotting a single band. Defaults to None.
vmax (float, optional): The maximum value to use when colormapping the palette when plotting a single band. Defaults to None.
nodata (float, optional): The value from the band to use to interpret as not valid data. Defaults to None.
attribution (str, optional): Attribution for the source raster. This defaults to a message about it being a local file.. Defaults to None.
layer_name (str, optional): The layer name to use. Defaults to None.
"""
if isinstance(source, str) and source.startswith("http"):
self.add_raster(
source,
band=band,
palette=palette,
vmin=vmin,
vmax=vmax,
nodata=nodata,
attribution=attribution,
layer_name=layer_name,
**kwargs,
)
else:
raise Exception("The source must be a URL.")
def add_heatmap(
self,
data,
latitude="latitude",
longitude="longitude",
value="value",
name="Heat map",
radius=25,
**kwargs,
):
"""Adds a heat map to the map. Reference: https://stackoverflow.com/a/54756617
Args:
data (str | list | pd.DataFrame): File path or HTTP URL to the input file or a list of data points in the format of [[x1, y1, z1], [x2, y2, z2]]. For example, https://raw.githubusercontent.com/giswqs/leafmap/master/examples/data/world_cities.csv
latitude (str, optional): The column name of latitude. Defaults to "latitude".
longitude (str, optional): The column name of longitude. Defaults to "longitude".
value (str, optional): The column name of values. Defaults to "value".
name (str, optional): Layer name to use. Defaults to "Heat map".
radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25.
Raises:
ValueError: If data is not a list.
"""
import pandas as pd
try:
if isinstance(data, str):
df = pd.read_csv(data)
data = df[[latitude, longitude, value]].values.tolist()
elif isinstance(data, pd.DataFrame):
data = data[[latitude, longitude, value]].values.tolist()
elif isinstance(data, list):
pass
else:
raise ValueError("data must be a list, a DataFrame, or a file path.")
plugins.HeatMap(data, name=name, radius=radius, **kwargs).add_to(
folium.FeatureGroup(name=name).add_to(self)
)
except Exception as e:
raise Exception(e)
def add_legend(
self,
title="Legend",
labels=None,
colors=None,
legend_dict=None,
builtin_legend=None,
opacity=1.0,
position="bottomright",
draggable=True,
style={},
):
"""Adds a customized legend to the map. Reference: https://bit.ly/3oV6vnH.
If you want to add multiple legends to the map, you need to set the `draggable` argument to False.
Args:
title (str, optional): Title of the legend. Defaults to 'Legend'. Defaults to "Legend".
colors (list, optional): A list of legend colors. Defaults to None.
labels (list, optional): A list of legend labels. Defaults to None.
legend_dict (dict, optional): A dictionary containing legend items as keys and color as values.
If provided, legend_keys and legend_colors will be ignored. Defaults to None.
builtin_legend (str, optional): Name of the builtin legend to add to the map. Defaults to None.
opacity (float, optional): The opacity of the legend. Defaults to 1.0.
position (str, optional): The position of the legend, can be one of the following:
"topleft", "topright", "bottomleft", "bottomright". Defaults to "bottomright".
draggable (bool, optional): If True, the legend can be dragged to a new position. Defaults to True.
style: Additional keyword arguments to style the legend, such as position, bottom, right, z-index,
border, background-color, border-radius, padding, font-size, etc. The default style is:
style = {
'position': 'fixed',
'z-index': '9999',
'border': '2px solid grey',
'background-color': 'rgba(255, 255, 255, 0.8)',
'border-radius': '5px',
'padding': '10px',
'font-size': '14px',
'bottom': '20px',
'right': '5px'
}
"""
content = create_legend(
title,
labels,
colors,
legend_dict,
builtin_legend,
opacity,
position,
draggable,
style=style,
)
if draggable:
from branca.element import Template, MacroElement
content = (
'"""\n{% macro html(this, kwargs) %}\n'
+ content
+ '\n{% endmacro %}"""'
)
macro = MacroElement()
macro._template = Template(content)
self.get_root().add_child(macro)
else:
self.add_html(content, position=position)
def add_colorbar(
self,
vis_params,
index=None,
label="",
categorical=False,
step=None,
background_color=None,
**kwargs,
):
"""Add a colorbar to the map.
Args:
colors (list): The set of colors to be used for interpolation. Colors can be provided in the form: * tuples of RGBA ints between 0 and 255 (e.g: (255, 255, 0) or (255, 255, 0, 255)) * tuples of RGBA floats between 0. and 1. (e.g: (1.,1.,0.) or (1., 1., 0., 1.)) * HTML-like string (e.g: “#ffff00) * a color name or shortcut (e.g: “y” or “yellow”)
vmin (int, optional): The minimal value for the colormap. Values lower than vmin will be bound directly to colors[0].. Defaults to 0.
vmax (float, optional): The maximal value for the colormap. Values higher than vmax will be bound directly to colors[-1]. Defaults to 1.0.
index (list, optional):The values corresponding to each color. It has to be sorted, and have the same length as colors. If None, a regular grid between vmin and vmax is created.. Defaults to None.
label (str, optional): The caption for the colormap. Defaults to "".
categorical (bool, optional): Whether or not to create a categorical colormap. Defaults to False.
step (int, optional): The step to split the LinearColormap into a StepColormap. Defaults to None.
"""
from box import Box
from branca.colormap import LinearColormap
if not isinstance(vis_params, dict):
raise ValueError("vis_params must be a dictionary.")
if "palette" not in vis_params:
raise ValueError("vis_params must contain a palette.")
if "min" not in vis_params:
vis_params["min"] = 0
if "max" not in vis_params:
vis_params["max"] = 1
colors = to_hex_colors(check_cmap(vis_params["palette"]))
vmin = vis_params["min"]
vmax = vis_params["max"]
if isinstance(colors, Box):
try:
colors = list(colors["default"])
except Exception as e:
print("The provided color list is invalid.")
raise Exception(e)
if all(len(color) == 6 for color in colors):
colors = ["#" + color for color in colors]
colormap = LinearColormap(
colors=colors, index=index, vmin=vmin, vmax=vmax, caption=label
)
if categorical:
if step is not None:
colormap = colormap.to_step(step)
elif index is not None:
colormap = colormap.to_step(len(index) - 1)
else:
colormap = colormap.to_step(3)
if background_color is not None:
svg_style = (
"<style>svg {background-color: " + background_color + ";}</style>"
)
self.get_root().header.add_child(folium.Element(svg_style))
self.add_child(colormap)
add_colorbar_branca = add_colorbar
def add_colormap(
self,
width=4.0,
height=0.3,
vmin=0,
vmax=1.0,
palette=None,
vis_params=None,
cmap="gray",
discrete=False,
label=None,
label_size=10,
label_weight="normal",
tick_size=8,
bg_color="white",
orientation="horizontal",
dpi="figure",
transparent=False,
position=(70, 5),
**kwargs,
):
"""Add a colorbar to the map. Under the hood, it uses matplotlib to generate the colorbar, save it as a png file, and add it to the map using m.add_image().
Args:
width (float): Width of the colorbar in inches. Default is 4.0.
height (float): Height of the colorbar in inches. Default is 0.3.
vmin (float): Minimum value of the colorbar. Default is 0.
vmax (float): Maximum value of the colorbar. Default is 1.0.
palette (list): List of colors to use for the colorbar. It can also be a cmap name, such as ndvi, ndwi, dem, coolwarm. Default is None.
vis_params (dict): Visualization parameters as a dictionary. See https://developers.google.com/earth-engine/guides/image_visualization for options.
cmap (str, optional): Matplotlib colormap. Defaults to "gray". See https://matplotlib.org/3.3.4/tutorials/colors/colormaps.html#sphx-glr-tutorials-colors-colormaps-py for options.
discrete (bool, optional): Whether to create a discrete colorbar. Defaults to False.
label (str, optional): Label for the colorbar. Defaults to None.
label_size (int, optional): Font size for the colorbar label. Defaults to 12.
label_weight (str, optional): Font weight for the colorbar label, can be "normal", "bold", etc. Defaults to "normal".
tick_size (int, optional): Font size for the colorbar tick labels. Defaults to 10.
bg_color (str, optional): Background color for the colorbar. Defaults to "white".
orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
dpi (float | str, optional): The resolution in dots per inch. If 'figure', use the figure's dpi value. Defaults to "figure".
transparent (bool, optional): Whether to make the background transparent. Defaults to False.
position (tuple, optional): The position of the colormap in the format of (x, y),
the percentage ranging from 0 to 100, starting from the lower-left corner. Defaults to (0, 0).
**kwargs: Other keyword arguments to pass to matplotlib.pyplot.savefig().
Returns:
str: Path to the output image.
"""
colorbar = save_colorbar(
None,
width,
height,
vmin,
vmax,
palette,
vis_params,
cmap,
discrete,
label,
label_size,
label_weight,
tick_size,
bg_color,
orientation,
dpi,
transparent,
show_colorbar=False,
**kwargs,
)
self.add_image(colorbar, position=position)
def add_styled_vector(
self,
ee_object,
column,
palette,
layer_name="Untitled",
shown=True,
opacity=1.0,
**kwargs,
):
"""Adds a styled vector to the map.
Args:
ee_object (object): An ee.FeatureCollection.
column (str): The column name to use for styling.
palette (list | dict): The palette (e.g., list of colors or a dict containing label and color pairs) to use for styling.
layer_name (str, optional): The name to be used for the new layer. Defaults to "Untitled".
"""
styled_vector = vector_styling(ee_object, column, palette, **kwargs)
self.addLayer(
styled_vector.style(**{"styleProperty": "style"}),
{},
layer_name,
shown,
opacity,
)
def add_shapefile(self, in_shp, layer_name="Untitled", **kwargs):
"""Adds a shapefile to the map. See https://python-visualization.github.io/folium/modules.html#folium.features.GeoJson for more info about setting style.
Args:
in_shp (str): The input file path to the shapefile.
layer_name (str, optional): The layer name to be used. Defaults to "Untitled".
Raises:
FileNotFoundError: The provided shapefile could not be found.
"""
in_shp = os.path.abspath(in_shp)
if not os.path.exists(in_shp):
raise FileNotFoundError("The provided shapefile could not be found.")
data = shp_to_geojson(in_shp)
geo_json = folium.GeoJson(data=data, name=layer_name, **kwargs)
geo_json.add_to(self)
def add_geojson(
self,
in_geojson,
layer_name="Untitled",
encoding="utf-8",
info_mode="on_hover",
fields=None,
**kwargs,
):
"""Adds a GeoJSON file to the map.
Args:
in_geojson (str): The input file path to the GeoJSON.
layer_name (str, optional): The layer name to be used. Defaults to "Untitled".
encoding (str, optional): The encoding of the GeoJSON file. Defaults to "utf-8".
info_mode (str, optional): Displays the attributes by either on_hover or on_click. Any value other than "on_hover" or "on_click" will be treated as None. Defaults to "on_hover".
fields (list, optional): The fields to be displayed in the popup. Defaults to None.
Raises:
FileNotFoundError: The provided GeoJSON file could not be found.
"""
import json
import requests
import random
try:
if isinstance(in_geojson, str):
if in_geojson.startswith("http"):
in_geojson = github_raw_url(in_geojson)
data = requests.get(in_geojson).json()
else:
in_geojson = os.path.abspath(in_geojson)
if not os.path.exists(in_geojson):
raise FileNotFoundError(
"The provided GeoJSON file could not be found."
)