-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
geemap.py
5093 lines (4386 loc) · 209 KB
/
geemap.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
"""Main module for interactive mapping using Google Earth Engine Python API and ipyleaflet.
Keep in mind that Earth Engine functions use both camel case and snake case,
such as setOptions(), setCenter(), centerObject(), addLayer().
ipyleaflet functions use snake case, such as add_tile_layer(), add_wms_layer(), add_minimap().
"""
# *******************************************************************************#
# This module contains core features and extra features of the geemap package. #
# The Earth Engine team and the geemap community will maintain the core features.#
# The geemap community will maintain the extra features. #
# The core features include classes and functions below until the line # ******* #
# *******************************************************************************#
import os
import warnings
from typing import Optional, Any, Dict
import ee
import ipyleaflet
import ipywidgets as widgets
from box import Box
from bqplot import pyplot as plt
from IPython.display import display
from .basemaps import get_xyz_dict, xyz_to_leaflet
from .common import *
from .conversion import *
from .ee_tile_layers import *
from . import core
from . import map_widgets
from . import toolbar
from .plot import *
from .timelapse import *
from .legends import builtin_legends
from . import examples
basemaps = Box(xyz_to_leaflet(), frozen_box=True)
class Map(core.Map):
"""The Map class inherits the core Map class. The arguments you can pass to the Map initialization
can be found at https://ipyleaflet.readthedocs.io/en/latest/map_and_basemaps/map.html.
By default, the Map will add Google Maps as the basemap. Set add_google_map = False
to use OpenStreetMap as the basemap.
Returns:
object: ipyleaflet map object.
"""
# Map attributes for drawing features
@property
def draw_control(self):
return self.get_draw_control()
@property
def draw_control_lite(self):
return self.get_draw_control()
@property
def draw_features(self):
return self._draw_control.features if self._draw_control else []
@property
def draw_last_feature(self):
return self._draw_control.last_feature if self._draw_control else None
@property
def draw_layer(self):
return self._draw_control.layer if self._draw_control else None
@property
def user_roi(self):
return self._draw_control.last_geometry if self._draw_control else None
@property
def user_rois(self):
return self._draw_control.collection if self._draw_control else None
def __init__(self, **kwargs):
"""Initialize a map object. The following additional parameters can be passed in addition to the ipyleaflet.Map parameters:
Args:
ee_initialize (bool, optional): Whether or not to initialize ee. Defaults to True.
center (list, optional): Center of the map (lat, lon). Defaults to [20, 0].
zoom (int, optional): Zoom level of the map. Defaults to 2.
height (str, optional): Height of the map. Defaults to "600px".
width (str, optional): Width of the map. Defaults to "100%".
basemap (str, optional): Name of the basemap to add to the map. Defaults to "ROADMAP". Other options include "ROADMAP", "SATELLITE", "TERRAIN".
add_google_map (bool, optional): Whether to add Google Maps to the map. Defaults to True.
sandbox_path (str, optional): The path to a sandbox folder for voila web app. Defaults to None.
lite_mode (bool, optional): Whether to enable lite mode, which only displays zoom control on the map. Defaults to False.
data_ctrl (bool, optional): Whether to add the data control to the map. Defaults to True.
zoom_ctrl (bool, optional): Whether to add the zoom control to the map. Defaults to True.
fullscreen_ctrl (bool, optional): Whether to add the fullscreen control to the map. Defaults to True.
search_ctrl (bool, optional): Whether to add the search control to the map. Defaults to True.
draw_ctrl (bool, optional): Whether to add the draw control to the map. Defaults to True.
scale_ctrl (bool, optional): Whether to add the scale control to the map. Defaults to True.
measure_ctrl (bool, optional): Whether to add the measure control to the map. Defaults to True.
toolbar_ctrl (bool, optional): Whether to add the toolbar control to the map. Defaults to True.
layer_ctrl (bool, optional): Whether to add the layer control to the map. Defaults to False.
attribution_ctrl (bool, optional): Whether to add the attribution control to the map. Defaults to True.
**kwargs: Additional keyword arguments for ipyleaflet.Map.
"""
warnings.filterwarnings("ignore")
if isinstance(kwargs.get("height"), int):
kwargs["height"] = str(kwargs["height"]) + "px"
if isinstance(kwargs.get("width"), int):
kwargs["width"] = str(kwargs["width"]) + "px"
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 24
self._xyz_dict = get_xyz_dict()
self.baseclass = "ipyleaflet"
self._USER_AGENT_PREFIX = "geemap"
self.kwargs = kwargs
super().__init__(**kwargs)
self._var_name = "Map" # The Map variable name for converting JS to Python
if kwargs.get("height"):
self.layout.height = kwargs.get("height")
# sandbox path for Voila app to restrict access to system directories.
if "sandbox_path" not in kwargs:
self.sandbox_path = None
else:
if os.path.exists(os.path.abspath(kwargs["sandbox_path"])):
self.sandbox_path = kwargs["sandbox_path"]
else:
print("The sandbox path is invalid.")
self.sandbox_path = None
# Add Google Maps as the default basemap
if kwargs.get("add_google_map", False):
self.add_basemap("ROADMAP")
# ipyleaflet built-in layer control
self.layer_control = None
if "ee_initialize" not in kwargs:
kwargs["ee_initialize"] = True
# Default reducer to use
if kwargs["ee_initialize"]:
self.roi_reducer = ee.Reducer.mean()
self.roi_reducer_scale = None
def _control_config(self):
if self.kwargs.get("lite_mode"):
return {"topleft": ["zoom_control"]}
topleft = []
bottomleft = []
topright = []
bottomright = []
for control in ["data_ctrl", "zoom_ctrl", "fullscreen_ctrl", "draw_ctrl"]:
if self.kwargs.get(control, True):
topleft.append(control)
for control in ["scale_ctrl", "measure_ctrl"]:
if self.kwargs.get(control, True):
bottomleft.append(control)
for control in ["toolbar_ctrl"]:
if self.kwargs.get(control, True):
topright.append(control)
for control in ["attribution_control"]:
if self.kwargs.get(control, True):
bottomright.append(control)
return {
"topleft": topleft,
"bottomleft": bottomleft,
"topright": topright,
"bottomright": bottomright,
}
@property
def ee_layer_names(self):
warnings.warn(
"ee_layer_names is deprecated. Use ee_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_layers.keys()
@property
def ee_layer_dict(self):
warnings.warn(
"ee_layer_dict is deprecated. Use ee_layers instead.", DeprecationWarning
)
return self.ee_layers
@property
def ee_raster_layer_names(self):
warnings.warn(
"ee_raster_layer_names is deprecated. Use self.ee_raster_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_raster_layers.keys()
@property
def ee_vector_layer_names(self):
warnings.warn(
"ee_vector_layer_names is deprecated. Use self.ee_vector_layers.keys() instead.",
DeprecationWarning,
)
return self.ee_vector_layers.keys()
@property
def ee_raster_layers(self):
return dict(filter(self._raster_filter, self.ee_layers.items()))
@property
def ee_vector_layers(self):
return dict(filter(self._vector_filter, self.ee_layers.items()))
def _raster_filter(self, pair):
return isinstance(pair[1]["ee_object"], (ee.Image, ee.ImageCollection))
def _vector_filter(self, pair):
return isinstance(
pair[1]["ee_object"], (ee.Geometry, ee.Feature, ee.FeatureCollection)
)
def add(self, obj, position="topright", **kwargs):
"""Adds a layer or control to the map.
Args:
object (object): The layer or control to add to the map.
"""
if isinstance(obj, str):
basemap = check_basemap(obj)
if basemap in basemaps.keys():
super().add(get_basemap(basemap))
return
if not isinstance(obj, str):
super().add(obj, position=position, **kwargs)
return
obj = obj.lower()
backward_compatibilities = {
"zoom_ctrl": "zoom_control",
"fullscreen_ctrl": "fullscreen_control",
"scale_ctrl": "scale_control",
"toolbar_ctrl": "toolbar",
"draw_ctrl": "draw_control",
}
obj = backward_compatibilities.get(obj, obj)
if obj == "data_ctrl":
data_widget = toolbar.SearchDataGUI(self)
data_control = ipyleaflet.WidgetControl(
widget=data_widget, position=position
)
self.add(data_control)
elif obj == "search_ctrl":
self.add_search_control(position=position)
elif obj == "measure_ctrl":
measure = ipyleaflet.MeasureControl(
position=position,
active_color="orange",
primary_length_unit="kilometers",
)
self.add(measure, position=position)
elif obj == "layer_ctrl":
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control, position=position)
else:
super().add(obj, position=position, **kwargs)
def add_controls(self, controls, position="topleft"):
"""Adds a list of controls to the map.
Args:
controls (list): A list of controls to add to the map.
position (str, optional): The position of the controls on the map. Defaults to 'topleft'.
"""
if not isinstance(controls, list):
controls = [controls]
for control in controls:
self.add(control, position)
def set_options(self, mapTypeId="HYBRID", **kwargs):
"""Adds Google basemap and controls to the ipyleaflet 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'.
"""
try:
self.add(mapTypeId)
except Exception:
raise ValueError(
'Google basemaps can only be one of "ROADMAP", "SATELLITE", "HYBRID" or "TERRAIN".'
)
setOptions = set_options
def add_ee_layer(
self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0
):
"""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 N'.
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.
"""
has_plot_dropdown = (
hasattr(self, "_plot_dropdown_widget")
and self._plot_dropdown_widget is not None
)
ee_layer = self.ee_layers.get(name, {})
layer = ee_layer.get("ee_layer", None)
if layer is not None:
if isinstance(ee_layer["ee_object"], (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(
self.ee_raster_layers.keys()
)
super().add_layer(ee_object, vis_params, name, shown, opacity)
if isinstance(ee_object, (ee.Image, ee.ImageCollection)):
if has_plot_dropdown:
self._plot_dropdown_widget.options = list(self.ee_raster_layers.keys())
tile_layer = self.ee_layers.get(name, {}).get("ee_layer", None)
if tile_layer:
arc_add_layer(tile_layer.url_format, name, shown, opacity)
addLayer = add_ee_layer
def remove_ee_layer(self, name):
"""Removes an Earth Engine layer.
Args:
name (str): The name of the Earth Engine layer to remove.
"""
if name in self.ee_layers:
ee_layer = self.ee_layers[name]["ee_layer"]
self.ee_layers.pop(name, None)
if ee_layer in self.layers:
self.remove_layer(ee_layer)
def set_center(self, lon, lat, zoom=None):
"""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 None.
"""
super().set_center(lon, lat, zoom)
if is_arcpy():
arc_zoom_to_extent(lon, lat, lon, lat)
setCenter = set_center
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.
"""
super().center_object(ee_object, zoom)
if is_arcpy():
bds = self.bounds
arc_zoom_to_extent(bds[0][1], bds[0][0], bds[1][1], bds[1][0])
centerObject = center_object
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 ipyleaflet 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 get_scale(self):
"""Returns the approximate pixel scale of the current map view, in meters.
Returns:
float: Map resolution in meters.
"""
return super().get_scale()
getScale = get_scale
def add_basemap(
self, basemap: Optional[str] = "ROADMAP", show: Optional[bool] = True, **kwargs
) -> None:
"""Adds a basemap to the map.
Args:
basemap (str, optional): Can be one of string from basemaps. Defaults to 'ROADMAP'.
show (bool, optional): Whether the basemap is visible or not. Defaults to True.
**kwargs: Keyword arguments for the TileLayer.
"""
import xyzservices
try:
layer_names = self.get_layer_names()
if isinstance(basemap, str):
for map_name, tile_provider in self._available_basemaps.items():
if basemap.upper() == map_name.upper():
basemap = tile_provider
break
if isinstance(basemap, xyzservices.TileProvider):
name = basemap.name
url = basemap.build_url()
attribution = basemap.attribution
if "max_zoom" in basemap.keys():
max_zoom = basemap["max_zoom"]
else:
max_zoom = 22
layer = ipyleaflet.TileLayer(
url=url,
name=name,
max_zoom=max_zoom,
attribution=attribution,
visible=show,
**kwargs,
)
self.add(layer)
arc_add_layer(url, name)
elif basemap in basemaps and basemaps[basemap].name not in layer_names:
self.add(basemap)
self.layers[-1].visible = show
arc_add_layer(basemaps[basemap].url, basemap)
elif basemap in basemaps and basemaps[basemap].name in layer_names:
print(f"{basemap} has been already added before.")
elif basemap.startswith("http"):
self.add_tile_layer(url=basemap, shown=show, **kwargs)
else:
print(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
except Exception as e:
raise ValueError(
"Basemap can only be one of the following:\n {}".format(
"\n ".join(basemaps.keys())
)
)
def get_layer_names(self):
"""Gets layer names as a list.
Returns:
list: A list of layer names.
"""
layer_names = []
for layer in list(self.layers):
if len(layer.name) > 0:
layer_names.append(layer.name)
return layer_names
def find_layer(self, name):
"""Finds layer by name
Args:
name (str): Name of the layer to find.
Returns:
object: ipyleaflet layer object.
"""
layers = self.layers
for layer in layers:
if layer.name == name:
return layer
return None
def show_layer(self, name, show=True):
"""Shows or hides a layer on the map.
Args:
name (str): Name of the layer to show/hide.
show (bool, optional): Whether to show or hide the layer. Defaults to True.
"""
layer = self.find_layer(name)
if layer is not None:
layer.visible = show
def find_layer_index(self, name):
"""Finds layer index by name
Args:
name (str): Name of the layer to find.
Returns:
int: Index of the layer with the specified name
"""
layers = self.layers
for index, layer in enumerate(layers):
if layer.name == name:
return index
return -1
def layer_opacity(self, name, opacity=1.0):
"""Changes layer opacity.
Args:
name (str): The name of the layer to change opacity.
opacity (float, optional): The opacity value to set. Defaults to 1.0.
"""
layer = self.find_layer(name)
try:
layer.opacity = opacity
except Exception as e:
raise Exception(e)
def add_tile_layer(
self,
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
name="Untitled",
attribution="",
opacity=1.0,
shown=True,
**kwargs,
):
"""Adds a TileLayer to the map.
Args:
url (str, optional): The URL of the tile layer. Defaults to 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'.
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.
"""
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 100
if "max_native_zoom" not in kwargs:
kwargs["max_native_zoom"] = 100
try:
tile_layer = ipyleaflet.TileLayer(
url=url,
name=name,
attribution=attribution,
opacity=opacity,
visible=shown,
**kwargs,
)
self.add(tile_layer)
except Exception as e:
print("Failed to add the specified TileLayer.")
raise Exception(e)
def set_plot_options(
self,
add_marker_cluster=False,
sample_scale=None,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Sets plotting options.
Args:
add_marker_cluster (bool, optional): Whether to add a marker cluster. Defaults to False.
sample_scale (float, optional): A nominal scale in meters of the projection to sample in . Defaults to None.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
plot_options_dict = {}
plot_options_dict["add_marker_cluster"] = add_marker_cluster
plot_options_dict["sample_scale"] = sample_scale
plot_options_dict["plot_type"] = plot_type
plot_options_dict["overlay"] = overlay
plot_options_dict["position"] = position
plot_options_dict["min_width"] = min_width
plot_options_dict["max_width"] = max_width
plot_options_dict["min_height"] = min_height
plot_options_dict["max_height"] = max_height
for key in kwargs:
plot_options_dict[key] = kwargs[key]
self._plot_options = plot_options_dict
if not hasattr(self, "_plot_marker_cluster"):
self._plot_marker_cluster = ipyleaflet.MarkerCluster(name="Marker Cluster")
if add_marker_cluster and (self._plot_marker_cluster not in self.layers):
self.add(self._plot_marker_cluster)
def plot(
self,
x,
y,
plot_type=None,
overlay=False,
position="bottomright",
min_width=None,
max_width=None,
min_height=None,
max_height=None,
**kwargs,
):
"""Creates a plot based on x-array and y-array data.
Args:
x (numpy.ndarray or list): The x-coordinates of the plotted line.
y (numpy.ndarray or list): The y-coordinates of the plotted line.
plot_type (str, optional): The plot type can be one of "None", "bar", "scatter" or "hist". Defaults to None.
overlay (bool, optional): Whether to overlay plotted lines on the figure. Defaults to False.
position (str, optional): Position of the control, can be ‘bottomleft’, ‘bottomright’, ‘topleft’, or ‘topright’. Defaults to 'bottomright'.
min_width (int, optional): Min width of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_width (int, optional): Max width of the widget (in pixels), if None it will respect the content size. Defaults to None.
min_height (int, optional): Min height of the widget (in pixels), if None it will respect the content size. Defaults to None.
max_height (int, optional): Max height of the widget (in pixels), if None it will respect the content size. Defaults to None.
"""
if hasattr(self, "_plot_widget") and self._plot_widget is not None:
plot_widget = self._plot_widget
else:
plot_widget = widgets.Output(
layout={"border": "1px solid black", "max_width": "500px"}
)
plot_control = ipyleaflet.WidgetControl(
widget=plot_widget,
position=position,
min_width=min_width,
max_width=max_width,
min_height=min_height,
max_height=max_height,
)
self._plot_widget = plot_widget
self._plot_control = plot_control
self.add(plot_control)
if max_width is None:
max_width = 500
if max_height is None:
max_height = 300
if (plot_type is None) and ("markers" not in kwargs):
kwargs["markers"] = "circle"
with plot_widget:
try:
fig = plt.figure(1, **kwargs)
if max_width is not None:
fig.layout.width = str(max_width) + "px"
if max_height is not None:
fig.layout.height = str(max_height) + "px"
plot_widget.outputs = ()
if not overlay:
plt.clear()
if plot_type is None:
if "marker" not in kwargs:
kwargs["marker"] = "circle"
plt.plot(x, y, **kwargs)
elif plot_type == "bar":
plt.bar(x, y, **kwargs)
elif plot_type == "scatter":
plt.scatter(x, y, **kwargs)
elif plot_type == "hist":
plt.hist(y, **kwargs)
plt.show()
except Exception as e:
print("Failed to create plot.")
raise Exception(e)
def add_layer_control(self, position="topright"):
"""Adds a layer control to the map.
Args:
position (str, optional): _description_. Defaults to "topright".
"""
if self.layer_control is None:
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control)
addLayerControl = add_layer_control
def add_legend(
self,
title="Legend",
legend_dict=None,
keys=None,
colors=None,
position="bottomright",
builtin_legend=None,
layer_name=None,
add_header=True,
widget_args={},
**kwargs,
):
"""Adds a customized basemap to the map.
Args:
title (str, optional): Title of the legend. Defaults to 'Legend'.
legend_dict (dict, optional): A dictionary containing legend items
as keys and color as values. If provided, keys and
colors will be ignored. Defaults to None.
keys (list, optional): A list of legend keys. Defaults to None.
colors (list, optional): A list of legend colors. Defaults to None.
position (str, optional): Position of the legend. Defaults to
'bottomright'.
builtin_legend (str, optional): Name of the builtin legend to add
to the map. Defaults to None.
add_header (bool, optional): Whether the legend can be closed or
not. Defaults to True.
widget_args (dict, optional): Additional arguments passed to the
widget_template() function. Defaults to {}.
"""
try:
legend = map_widgets.Legend(
title,
legend_dict,
keys,
colors,
position,
builtin_legend,
add_header,
widget_args,
**kwargs,
)
legend_control = ipyleaflet.WidgetControl(widget=legend, position=position)
self._legend_widget = legend
self._legend = legend_control
self.add(legend_control)
if not hasattr(self, "legends"):
setattr(self, "legends", [legend_control])
else:
self.legends.append(legend_control)
if layer_name in self.ee_layers:
self.ee_layers[layer_name]["legend"] = legend_control
except Exception as e:
raise Exception(e)
def add_colorbar(
self,
vis_params=None,
cmap="gray",
discrete=False,
label=None,
orientation="horizontal",
position="bottomright",
transparent_bg=False,
layer_name=None,
font_size=9,
axis_off=False,
max_width=None,
**kwargs,
):
"""Add a matplotlib colorbar to the map
Args:
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.
orientation (str, optional): Orientation of the colorbar, such as "vertical" and "horizontal". Defaults to "horizontal".
position (str, optional): Position of the colorbar on the map. It can be one of: topleft, topright, bottomleft, and bottomright. Defaults to "bottomright".
transparent_bg (bool, optional): Whether to use transparent background. Defaults to False.
layer_name (str, optional): The layer name associated with the colorbar. Defaults to None.
font_size (int, optional): Font size for the colorbar. Defaults to 9.
axis_off (bool, optional): Whether to turn off the axis. Defaults to False.
max_width (str, optional): Maximum width of the colorbar in pixels. Defaults to None.
Raises:
TypeError: If the vis_params is not a dictionary.
ValueError: If the orientation is not either horizontal or vertical.
TypeError: If the provided min value is not scalar type.
TypeError: If the provided max value is not scalar type.
TypeError: If the provided opacity value is not scalar type.
TypeError: If cmap or palette is not provided.
"""
colorbar = map_widgets.Colorbar(
vis_params,
cmap,
discrete,
label,
orientation,
transparent_bg,
font_size,
axis_off,
max_width,
**kwargs,
)
colormap_ctrl = ipyleaflet.WidgetControl(
widget=colorbar, position=position, transparent_bg=transparent_bg
)
self._colorbar = colormap_ctrl
if layer_name in self.ee_layers:
if "colorbar" in self.ee_layers[layer_name]:
self.remove_control(self.ee_layers[layer_name]["colorbar"])
self.ee_layers[layer_name]["colorbar"] = colormap_ctrl
if not hasattr(self, "colorbars"):
self.colorbars = [colormap_ctrl]
else:
self.colorbars.append(colormap_ctrl)
self.add(colormap_ctrl)
def remove_colorbar(self):
"""Remove colorbar from the map."""
if hasattr(self, "_colorbar") and self._colorbar is not None:
self.remove_control(self._colorbar)
def remove_colorbars(self):
"""Remove all colorbars from the map."""
if hasattr(self, "colorbars"):
for colorbar in self.colorbars:
if colorbar in self.controls:
self.remove_control(colorbar)
def remove_legend(self):
"""Remove legend from the map."""
if hasattr(self, "_legend") and self._legend is not None:
if self._legend in self.controls:
self.remove_control(self._legend)
def remove_legends(self):
"""Remove all legends from the map."""
if hasattr(self, "legends"):
for legend in self.legends:
if legend in self.controls:
self.remove_control(legend)
def create_vis_widget(self, layer_dict):
"""Create a GUI for changing layer visualization parameters interactively.
Args:
layer_dict (dict): A dict containing information about the layer. It is an element from Map.ee_layers.
"""
self._add_layer_editor(position="topright", layer_dict=layer_dict)
def add_inspector(
self,
names=None,
visible=True,
decimals=2,
position="topright",
opened=True,
show_close_button=True,
):
"""Add the Inspector GUI to the map.
Args:
names (str | list, optional): The names of the layers to be included. Defaults to None.
visible (bool, optional): Whether to inspect visible layers only. Defaults to True.
decimals (int, optional): The number of decimal places to round the coordinates. Defaults to 2.
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
"""
super()._add_inspector(
position,
names=names,
visible=visible,
decimals=decimals,
opened=opened,
show_close_button=show_close_button,
)
def add_layer_manager(
self, position="topright", opened=True, show_close_button=True
):
"""Add the Layer Manager to the map.
Args:
position (str, optional): The position of the Layer Manager. Defaults to "topright".
opened (bool, optional): Whether the control is opened. Defaults to True.
show_close_button (bool, optional): Whether to show the close button. Defaults to True.
"""
super()._add_layer_manager(position)
if layer_manager := self._layer_manager:
layer_manager.collapsed = not opened
layer_manager.close_button_hidden = not show_close_button
def _on_basemap_changed(self, basemap_name):
if basemap_name not in self.get_layer_names():
self.add_basemap(basemap_name)
if basemap_name in self._xyz_dict:
if "bounds" in self._xyz_dict[basemap_name]:
bounds = self._xyz_dict[basemap_name]["bounds"]
bounds = [bounds[0][1], bounds[0][0], bounds[1][1], bounds[1][0]]
self.zoom_to_bounds(bounds)
def add_basemap_widget(self, position="topright"):
"""Add the Basemap GUI to the map.
Args:
position (str, optional): The position of the Inspector GUI. Defaults to "topright".
"""
super()._add_basemap_selector(position=position)
def add_draw_control(self, position="topleft"):
"""Add a draw control to the map
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add("draw_control", position=position)
def add_draw_control_lite(self, position="topleft"):
"""Add a lite version draw control to the map for the plotting tool.
Args:
position (str, optional): The position of the draw control. Defaults to "topleft".
"""
super().add(
"draw_control",
position=position,
marker={},
rectangle={"shapeOptions": {"color": "#3388ff"}},
circle={"shapeOptions": {"color": "#3388ff"}},
circlemarker={},
polyline={},
polygon={},
edit=False,
remove=False,
)
def add_toolbar(self, position="topright", **kwargs):
"""Add a toolbar to the map.
Args:
position (str, optional): The position of the toolbar. Defaults to "topright".
"""
self.add("toolbar", position, **kwargs)
def _toolbar_main_tools(self):
return toolbar.main_tools
def _toolbar_extra_tools(self):
return toolbar.extra_tools
def add_plot_gui(self, position="topright", **kwargs):
"""Adds the plot widget to the map.
Args:
position (str, optional): Position of the widget. Defaults to "topright".
"""
from .toolbar import ee_plot_gui
ee_plot_gui(self, position, **kwargs)
def add_gui(
self, name, position="topright", opened=True, show_close_button=True, **kwargs
):
"""Add a GUI to the map.
Args:
name (str): The name of the GUI. Options include "layer_manager", "inspector", "plot", and "timelapse".
position (str, optional): The position of the GUI. Defaults to "topright".
opened (bool, optional): Whether the GUI is opened. Defaults to True.