/
geemap.py
6945 lines (5978 loc) · 281 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
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 xyz_to_leaflet
from .common import *
from .conversion import *
from .ee_tile_layers import *
from .timelapse import *
from .plot import *
from . import examples
basemaps = Box(xyz_to_leaflet(), frozen_box=True)
class Map(ipyleaflet.Map):
"""The Map class inherits the ipyleaflet 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.
"""
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")
# Authenticates Earth Engine and initializes an Earth Engine session
if "ee_initialize" not in kwargs:
kwargs["ee_initialize"] = True
if kwargs["ee_initialize"]:
ee_initialize()
# Default map center center (lat, lon) and zoom level
center = [20, 0]
zoom = 2
# Set map width and height
if "height" not in kwargs:
kwargs["height"] = "600px"
elif isinstance(kwargs["height"], int):
kwargs["height"] = str(kwargs["height"]) + "px"
if "width" in kwargs and isinstance(kwargs["width"], int):
kwargs["width"] = str(kwargs["width"]) + "px"
# Set map center and zoom level
if "center" not in kwargs:
kwargs["center"] = center
if "zoom" not in kwargs:
kwargs["zoom"] = zoom
if "max_zoom" not in kwargs:
kwargs["max_zoom"] = 24
# Enable scroll wheel zoom by default
if "scroll_wheel_zoom" not in kwargs:
kwargs["scroll_wheel_zoom"] = True
# Use any basemap available through the basemap module, such as 'ROADMAP', 'OpenTopoMap'
if "basemap" in kwargs:
kwargs["basemap"] = check_basemap(kwargs["basemap"])
if kwargs["basemap"] in basemaps.keys():
kwargs["basemap"] = get_basemap(kwargs["basemap"])
kwargs["add_google_map"] = False
else:
kwargs.pop("basemap")
# Inherits the ipyleaflet Map class
super().__init__(**kwargs)
self.baseclass = "ipyleaflet"
self.layout.height = kwargs["height"]
if "width" in kwargs:
self.layout.width = kwargs["width"]
# 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", True):
self.add("Google Maps")
# Remove all default controls
self.clear_controls()
if kwargs.get("lite_mode"): # Lite mode with only the zoom control
self.add_controls("zoom_ctrl", position="topleft")
else: # full mode with all controls
topleft_controls = [
"data_ctrl",
"zoom_ctrl",
"fullscreen_ctrl",
"draw_ctrl",
]
bottomleft_controls = [
"scale_ctrl",
"measure_ctrl",
]
topright_controls = [
"toolbar_ctrl",
]
bottomright_controls = ["attribution_ctrl"]
for control in topleft_controls:
if kwargs.get(control, True):
self.add_controls(control, position="topleft")
for control in bottomleft_controls:
if kwargs.get(control, True):
self.add_controls(control, position="bottomleft")
for control in topright_controls:
if kwargs.get(control, True):
self.add_controls(control, position="topright")
for control in bottomright_controls:
if kwargs.get(control, True):
self.add_controls(control, position="bottomright")
# Map attributes for drawing features
self.draw_features = []
self.draw_last_feature = None
self.draw_layer = None
self.user_roi = None
self.user_rois = None
# Map attributes for layers
self.geojson_layers = []
self.ee_layers = []
self.ee_layer_names = []
self.ee_raster_layers = []
self.ee_raster_layer_names = []
self.ee_vector_layers = []
self.ee_vector_layer_names = []
self.ee_layer_dict = {}
# ipyleaflet built-in layer control
self.layer_control = None
# Default reducer to use
if kwargs["ee_initialize"]:
self.roi_reducer = ee.Reducer.mean()
self.roi_reducer_scale = None
def add(self, object):
"""Adds a layer or control to the map.
Args:
object (object): The layer or control to add to the map.
"""
if isinstance(object, str):
object = check_basemap(object)
if object in basemaps.keys():
object = get_basemap(object)
super().add(object)
if hasattr(self, "layer_manager_widget"):
self.update_layer_manager()
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:
if isinstance(control, str):
control = control.lower()
if control == "data_ctrl":
from .toolbar import search_data_gui
search_data_gui(self, position=position)
elif control == "zoom_ctrl":
self.add(ipyleaflet.ZoomControl(position=position))
elif control == "fullscreen_ctrl":
fullscreen = ipyleaflet.FullScreenControl(position=position)
self.add(fullscreen)
elif control == "search_ctrl":
self.add_search_control(position=position)
elif control == "draw_ctrl":
self.add_draw_control(position=position)
elif control == "scale_ctrl":
scale_control = ipyleaflet.ScaleControl(position=position)
self.add(scale_control)
elif control == "measure_ctrl":
measure = ipyleaflet.MeasureControl(
position=position,
active_color="orange",
primary_length_unit="kilometers",
)
self.add(measure)
elif control == "toolbar_ctrl":
self.add_toolbar(position=position)
elif control == "layer_ctrl":
layer_control = ipyleaflet.LayersControl(position=position)
self.add(layer_control)
elif control == "attribution_ctrl":
attribution = ipyleaflet.AttributionControl(position=position)
self.add(attribution)
else:
raise ValueError(f"Unsupported control: {control}")
else:
self.add(control)
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.
"""
if name is None:
layer_count = len(self.layers)
name = "Layer " + str(layer_count + 1)
tile_layer = EELeafletTileLayer(ee_object, vis_params, name, shown, opacity)
layer = self.find_layer(name=name)
if layer is not None:
existing_object = self.ee_layer_dict[name]["ee_object"]
if isinstance(existing_object, (ee.Image, ee.ImageCollection)):
self.ee_raster_layers.remove(existing_object)
self.ee_raster_layer_names.remove(name)
if (
hasattr(self, "_plot_dropdown_widget")
and self._plot_dropdown_widget is not None
):
self._plot_dropdown_widget.options = list(
self.ee_raster_layer_names
)
elif isinstance(ee_object, (ee.Geometry, ee.Feature, ee.FeatureCollection)):
self.ee_vector_layers.remove(existing_object)
self.ee_vector_layer_names.remove(name)
self.ee_layers.remove(existing_object)
self.ee_layer_names.remove(name)
self.remove_layer(layer)
self.ee_layers.append(ee_object)
if name not in self.ee_layer_names:
self.ee_layer_names.append(name)
self.ee_layer_dict[name] = {
"ee_object": ee_object,
"ee_layer": tile_layer,
"vis_params": vis_params,
}
self.add(tile_layer)
if isinstance(ee_object, (ee.Image, ee.ImageCollection)):
self.ee_raster_layers.append(ee_object)
self.ee_raster_layer_names.append(name)
if (
hasattr(self, "_plot_dropdown_widget")
and self._plot_dropdown_widget is not None
):
self._plot_dropdown_widget.options = list(self.ee_raster_layer_names)
elif isinstance(ee_object, (ee.Geometry, ee.Feature, ee.FeatureCollection)):
self.ee_vector_layers.append(ee_object)
self.ee_vector_layer_names.append(name)
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_layer_dict:
ee_object = self.ee_layer_dict[name]["ee_object"]
ee_layer = self.ee_layer_dict[name]["ee_layer"]
if name in self.ee_raster_layer_names:
self.ee_raster_layer_names.remove(name)
self.ee_raster_layers.remove(ee_object)
elif name in self.ee_vector_layer_names:
self.ee_vector_layer_names.remove(name)
self.ee_vector_layers.remove(ee_object)
self.ee_layers.remove(ee_object)
self.ee_layer_names.remove(name)
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.
"""
self.center = (lat, lon)
if zoom is not None:
self.zoom = 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.
"""
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 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.
"""
import math
zoom_level = self.zoom
center_lat = self.center[0]
# Reference:
# - https://blogs.bing.com/maps/2006/02/25/map-control-zoom-levels-gt-resolution
# - https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Resolution_and_Scale
center_lat_cos = math.cos(math.radians(center_lat))
resolution = 156543.04 * center_lat_cos / math.pow(2, zoom_level)
return resolution
getScale = get_scale
def add_basemap(self, basemap="HYBRID", show=True, **kwargs):
"""Adds a basemap to the map.
Args:
basemap (str, optional): Can be one of string from basemaps. Defaults to 'HYBRID'.
visible (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()
map_dict = {
"ROADMAP": "Google Maps",
"SATELLITE": "Google Satellite",
"TERRAIN": "Google Terrain",
"HYBRID": "Google Hybrid",
}
if isinstance(basemap, str):
if basemap.upper() in map_dict:
basemap = map_dict[basemap.upper()]
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.")
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"})
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,
labels=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, legend_keys and legend_colors will be ignored. Defaults to None.
labels (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.
layer_name (str, optional): Layer name of the legend to be associated with. 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 {}.
"""
from IPython.display import display
import pkg_resources
from .legends import builtin_legends
pkg_dir = os.path.dirname(
pkg_resources.resource_filename("geemap", "geemap.py")
)
legend_template = os.path.join(pkg_dir, "data/template/legend.html")
if "min_width" not in kwargs:
min_width = None
if "max_width" not in kwargs:
max_width = None
else:
max_width = kwargs["max_width"]
if "min_height" not in kwargs:
min_height = None
else:
min_height = kwargs["min_height"]
if "max_height" not in kwargs:
max_height = None
else:
max_height = kwargs["max_height"]
if "height" not in kwargs:
height = None
else:
height = kwargs["height"]
if "width" not in kwargs:
width = None
else:
width = kwargs["width"]
if width is None:
max_width = "300px"
if height is None:
max_height = "400px"
if not os.path.exists(legend_template):
print("The legend template does not exist.")
return
if labels is not None:
if not isinstance(labels, list):
print("The legend keys must be a list.")
return
else:
labels = ["One", "Two", "Three", "Four", "etc"]
if colors is not None:
if not isinstance(colors, list):
print("The legend colors must be a list.")
return
elif all(isinstance(item, tuple) for item in colors):
try:
colors = [rgb_to_hex(x) for x in colors]
except Exception as e:
print(e)
elif all((item.startswith("#") and len(item) == 7) for item in colors):
pass
elif all((len(item) == 6) for item in colors):
pass
else:
print("The legend colors must be a list of tuples.")
return
else:
colors = [
"#8DD3C7",
"#FFFFB3",
"#BEBADA",
"#FB8072",
"#80B1D3",
]
if len(labels) != len(colors):
print("The legend keys and values must be the same length.")
return
allowed_builtin_legends = builtin_legends.keys()
if builtin_legend is not None:
if builtin_legend not in allowed_builtin_legends:
print(
"The builtin legend must be one of the following: {}".format(
", ".join(allowed_builtin_legends)
)
)
return
else:
legend_dict = builtin_legends[builtin_legend]
labels = list(legend_dict.keys())
colors = list(legend_dict.values())
if legend_dict is not None:
if not isinstance(legend_dict, dict):
print("The legend dict must be a dictionary.")
return
else:
labels = list(legend_dict.keys())
colors = list(legend_dict.values())
if all(isinstance(item, tuple) for item in colors):
try:
colors = [rgb_to_hex(x) for x in colors]
except Exception as e:
print(e)
allowed_positions = [
"topleft",
"topright",
"bottomleft",
"bottomright",
]
if position not in allowed_positions:
print(
"The position must be one of the following: {}".format(
", ".join(allowed_positions)
)
)
return
header = []
content = []
footer = []
with open(legend_template) as f:
lines = f.readlines()
lines[3] = lines[3].replace("Legend", title)
header = lines[:6]
footer = lines[11:]
for index, key in enumerate(labels):
color = colors[index]
if not color.startswith("#"):
color = "#" + color
item = " <li><span style='background:{};'></span>{}</li>\n".format(
color, key
)
content.append(item)
legend_html = header + content + footer
legend_text = "".join(legend_html)
try:
legend_output = widgets.Output(
layout={
# "border": "1px solid black",
"max_width": max_width,
"min_width": min_width,
"max_height": max_height,
"min_height": min_height,
"height": height,
"width": width,
"overflow": "scroll",
}
)
legend_widget = widgets.HTML(value=legend_text)
if add_header:
if "show_close_button" not in widget_args:
widget_args["show_close_button"] = False
if "widget_icon" not in widget_args:
widget_args["widget_icon"] = "bars"
legend_output_widget = widget_template(
legend_output,
position=position,
display_widget=legend_widget,
**widget_args,
)
else:
legend_output_widget = legend_output
legend_control = ipyleaflet.WidgetControl(
widget=legend_output_widget, position=position
)
# legend_output.append_display_data(legend_widget)
with legend_output:
display(legend_widget)
self._legend_widget = legend_output_widget
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_layer_names:
self.ee_layer_dict[layer_name]["legend"] = legend_control
except Exception as e:
raise Exception(e)