-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
toolbar.py
5024 lines (4259 loc) · 168 KB
/
toolbar.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 dealing with the toolbar.
"""
import os
import ee
import ipyevents
import ipyleaflet
import ipywidgets as widgets
from ipyfilechooser import FileChooser
from IPython.core.display import display
from .common import *
from .timelapse import *
def tool_template(m=None, opened=True):
"""Create a toolbar widget.
Args:
m (geemap.Map, optional): The geemap.Map instance. Defaults to None.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
"""
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gear",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
checkbox = widgets.Checkbox(
description="Checkbox",
indent=False,
layout=widgets.Layout(padding=padding, width=widget_width),
)
dropdown = widgets.Dropdown(
options=["Option 1", "Option 2", "Option 3"],
value=None,
description="Dropdown:",
layout=widgets.Layout(width=widget_width, padding=padding),
style={"description_width": "initial"},
)
int_slider = widgets.IntSlider(
min=1,
max=100,
description="Int Slider: ",
readout=False,
continuous_update=True,
layout=widgets.Layout(width="220px", padding=padding),
style={"description_width": "initial"},
)
int_slider_label = widgets.Label(str(int_slider.value))
def update_int_slider(change):
int_slider_label.value = str(change["new"])
int_slider.observe(update_int_slider, "value")
float_slider = widgets.FloatSlider(
min=1,
max=100,
description="Float Slider: ",
readout=False,
continuous_update=True,
layout=widgets.Layout(width="210px", padding=padding),
style={"description_width": "initial"},
)
float_slider_label = widgets.Label(str(float_slider.value))
def update_float_slider(change):
float_slider_label.value = str(change["new"])
float_slider.observe(update_float_slider, "value")
color = widgets.ColorPicker(
concise=False,
description="Color:",
value="white",
style={"description_width": "initial"},
layout=widgets.Layout(width=widget_width, padding=padding),
)
text = widgets.Text(
value="",
description="Textbox:",
placeholder="Placeholder",
style={"description_width": "initial"},
layout=widgets.Layout(width=widget_width, padding=padding),
)
textarea = widgets.Textarea(
placeholder="Placeholder",
layout=widgets.Layout(width=widget_width, padding=padding),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
checkbox,
widgets.HBox([int_slider, int_slider_label]),
widgets.HBox([float_slider, float_slider_label]),
dropdown,
text,
color,
textarea,
buttons,
output,
]
# toolbar_event = ipyevents.Event(
# source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
# )
# def handle_toolbar_event(event):
# if event["type"] == "mouseenter":
# toolbar_widget.children = [toolbar_header, toolbar_footer]
# elif event["type"] == "mouseleave":
# if not toolbar_button.value:
# toolbar_widget.children = [toolbar_button]
# toolbar_button.value = False
# close_button.value = False
# toolbar_event.on_dom_event(handle_toolbar_event)
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Apply":
with output:
output.clear_output()
print("Running ...")
elif change["new"] == "Reset":
textarea.value = ""
output.clear_output()
elif change["new"] == "Close":
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = opened
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
else:
return toolbar_widget
def tool_header_template(m=None, opened=True):
"""Create a toolbar widget.
Args:
m (geemap.Map, optional): The geemap.Map instance. Defaults to None.
opened (bool, optional): Whether to open the toolbar. Defaults to True.
"""
widget_width = "250px"
padding = "0px 0px 0px 5px" # upper, right, bottom, left
toolbar_button = widgets.ToggleButton(
value=False,
tooltip="Toolbar",
icon="gear",
layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
)
close_button = widgets.ToggleButton(
value=False,
tooltip="Close the tool",
icon="times",
button_style="primary",
layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
buttons.style.button_width = "80px"
output = widgets.Output(layout=widgets.Layout(width=widget_width, padding=padding))
toolbar_widget = widgets.VBox()
toolbar_widget.children = [toolbar_button]
toolbar_header = widgets.HBox()
toolbar_header.children = [close_button, toolbar_button]
toolbar_footer = widgets.VBox()
toolbar_footer.children = [
buttons,
output,
]
def toolbar_btn_click(change):
if change["new"]:
close_button.value = False
toolbar_widget.children = [toolbar_header, toolbar_footer]
else:
if not close_button.value:
toolbar_widget.children = [toolbar_button]
toolbar_button.observe(toolbar_btn_click, "value")
def close_btn_click(change):
if change["new"]:
toolbar_button.value = False
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
close_button.observe(close_btn_click, "value")
def button_clicked(change):
if change["new"] == "Apply":
with output:
output.clear_output()
print("Running ...")
elif change["new"] == "Reset":
output.clear_output()
elif change["new"] == "Close":
if m is not None:
m.toolbar_reset()
if m.tool_control is not None and m.tool_control in m.controls:
m.remove_control(m.tool_control)
m.tool_control = None
toolbar_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
toolbar_button.value = opened
if m is not None:
toolbar_control = ipyleaflet.WidgetControl(
widget=toolbar_widget, position="topright"
)
if toolbar_control not in m.controls:
m.add_control(toolbar_control)
m.tool_control = toolbar_control
else:
return toolbar_widget
def open_data_widget(m):
"""A widget for opening local vector/raster data.
Args:
m (object): geemap.Map
"""
from .colormaps import list_colormaps
padding = "0px 0px 0px 5px"
style = {"description_width": "initial"}
tool_output = widgets.Output()
tool_output_ctrl = ipyleaflet.WidgetControl(widget=tool_output, position="topright")
if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls:
m.remove_control(m.tool_output_ctrl)
file_type = widgets.ToggleButtons(
options=["Shapefile", "GeoJSON", "CSV", "Vector", "Raster"],
tooltips=[
"Open a shapefile",
"Open a GeoJSON file",
"Open a vector dataset",
"Create points from CSV",
"Open a vector dataset",
"Open a raster dataset",
],
)
file_type.style.button_width = "88px"
filepath = widgets.Text(
value="",
description="File path or http URL:",
tooltip="Enter a file path or http URL to vector data",
style=style,
layout=widgets.Layout(width="454px", padding=padding),
)
http_widget = widgets.HBox()
file_chooser = FileChooser(
os.getcwd(), sandbox_path=m.sandbox_path, layout=widgets.Layout(width="454px")
)
file_chooser.filter_pattern = "*.shp"
file_chooser.use_dir_icons = True
style = {"description_width": "initial"}
layer_name = widgets.Text(
value="Shapefile",
description="Enter a layer name:",
tooltip="Enter a layer name for the selected file",
style=style,
layout=widgets.Layout(width="454px", padding="0px 0px 0px 5px"),
)
longitude = widgets.Dropdown(
options=[],
value=None,
description="Longitude:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
latitude = widgets.Dropdown(
options=[],
value=None,
description="Latitude:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
label = widgets.Dropdown(
options=[],
value=None,
description="Label:",
layout=widgets.Layout(width="149px", padding="0px 0px 0px 5px"),
style={"description_width": "initial"},
)
csv_widget = widgets.HBox()
convert_bool = widgets.Checkbox(
description="Convert to ee.FeatureCollection?",
indent=False,
layout=widgets.Layout(padding="0px 0px 0px 5px"),
)
convert_hbox = widgets.HBox([convert_bool])
ok_cancel = widgets.ToggleButtons(
value=None,
options=["Apply", "Reset", "Close"],
tooltips=["Apply", "Reset", "Close"],
button_style="primary",
)
# ok_cancel.style.button_width = "133px"
bands = widgets.Text(
value=None,
description="Band:",
tooltip="Enter a list of band indices",
style=style,
layout=widgets.Layout(width="150px", padding=padding),
)
vmin = widgets.Text(
value=None,
description="vmin:",
tooltip="Minimum value of the raster to visualize",
style=style,
layout=widgets.Layout(width="148px"),
)
vmax = widgets.Text(
value=None,
description="vmax:",
tooltip="Maximum value of the raster to visualize",
style=style,
layout=widgets.Layout(width="148px"),
)
nodata = widgets.Text(
value=None,
description="Nodata:",
tooltip="Nodata the raster to visualize",
style=style,
layout=widgets.Layout(width="150px", padding=padding),
)
palette = widgets.Dropdown(
options=[],
value=None,
description="palette:",
layout=widgets.Layout(width="300px"),
style=style,
)
raster_options = widgets.VBox()
main_widget = widgets.VBox(
[
file_type,
file_chooser,
http_widget,
csv_widget,
layer_name,
convert_hbox,
raster_options,
ok_cancel,
]
)
tool_output.clear_output()
with tool_output:
display(main_widget)
def bands_changed(change):
if change["new"] and "," in change["owner"].value:
palette.value = None
palette.disabled = True
else:
palette.disabled = False
bands.observe(bands_changed, "value")
def chooser_callback(chooser):
filepath.value = file_chooser.selected
if file_type.value == "CSV":
import pandas as pd
df = pd.read_csv(filepath.value)
col_names = df.columns.values.tolist()
longitude.options = col_names
latitude.options = col_names
label.options = col_names
if "longitude" in col_names:
longitude.value = "longitude"
if "latitude" in col_names:
latitude.value = "latitude"
if "name" in col_names:
label.value = "name"
file_chooser.register_callback(chooser_callback)
def file_type_changed(change):
ok_cancel.value = None
file_chooser.default_path = os.getcwd()
file_chooser.reset()
layer_name.value = file_type.value
csv_widget.children = []
filepath.value = ""
if change["new"] == "Shapefile":
file_chooser.filter_pattern = "*.shp"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = []
elif change["new"] == "GeoJSON":
file_chooser.filter_pattern = "*.geojson"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "Vector":
file_chooser.filter_pattern = "*.*"
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "CSV":
file_chooser.filter_pattern = ["*.csv", "*.CSV"]
csv_widget.children = [longitude, latitude, label]
raster_options.children = []
convert_hbox.children = [convert_bool]
http_widget.children = [filepath]
elif change["new"] == "Raster":
file_chooser.filter_pattern = ["*.tif", "*.img"]
palette.options = list_colormaps(add_extra=True)
palette.value = None
raster_options.children = [
widgets.HBox([bands, vmin, vmax]),
widgets.HBox([nodata, palette]),
]
convert_hbox.children = []
http_widget.children = [filepath]
def ok_cancel_clicked(change):
if change["new"] == "Apply":
m.default_style = {"cursor": "wait"}
file_path = filepath.value
if file_path is not None:
ext = os.path.splitext(file_path)[1]
with tool_output:
if ext.lower() == ".shp":
if convert_bool.value:
ee_object = shp_to_ee(file_path)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_shapefile(
file_path, style={}, layer_name=layer_name.value
)
elif ext.lower() == ".geojson":
if convert_bool.value:
ee_object = geojson_to_ee(file_path)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_geojson(
file_path, style={}, layer_name=layer_name.value
)
elif ext.lower() == ".csv":
if convert_bool.value:
ee_object = csv_to_ee(
file_path, latitude.value, longitude.value
)
m.addLayer(ee_object, {}, layer_name.value)
else:
m.add_xy_data(
file_path,
x=longitude.value,
y=latitude.value,
label=label.value,
layer_name=layer_name.value,
)
elif ext.lower() in [".tif", "img"] and file_type.value == "Raster":
band = None
vis_min = None
vis_max = None
vis_nodata = None
try:
if len(bands.value) > 0:
band = bands.value.split(",")
if len(vmin.value) > 0:
vis_min = float(vmin.value)
if len(vmax.value) > 0:
vis_max = float(vmax.value)
if len(nodata.value) > 0:
vis_nodata = float(nodata.value)
except Exception as _:
pass
m.add_local_tile(
file_path,
layer_name=layer_name.value,
band=band,
palette=palette.value,
vmin=vis_min,
vmax=vis_max,
nodata=vis_nodata,
)
else:
m.add_vector(file_path, style={}, layer_name=layer_name.value)
else:
print("Please select a file to open.")
m.toolbar_reset()
m.default_style = {"cursor": "default"}
elif change["new"] == "Reset":
file_chooser.reset()
tool_output.clear_output()
with tool_output:
display(main_widget)
m.toolbar_reset()
elif change["new"] == "Close":
if m.tool_output_ctrl is not None and m.tool_output_ctrl in m.controls:
m.remove_control(m.tool_output_ctrl)
m.tool_output_ctrl = None
m.toolbar_reset()
ok_cancel.value = None
file_type.observe(file_type_changed, names="value")
ok_cancel.observe(ok_cancel_clicked, names="value")
# file_chooser.register_callback(chooser_callback)
m.add_control(tool_output_ctrl)
m.tool_output_ctrl = tool_output_ctrl
def change_basemap(m):
"""Widget for changing basemaps.
Args:
m (object): leafmap.Map.
"""
from .basemaps import get_xyz_dict
from .geemap import basemaps, get_basemap
xyz_dict = get_xyz_dict()
value = "OpenStreetMap"
dropdown = widgets.Dropdown(
options=list(basemaps.keys()),
value=value,
layout=widgets.Layout(width="200px"),
)
close_btn = widgets.Button(
icon="times",
tooltip="Close the basemap widget",
button_style="primary",
layout=widgets.Layout(width="32px"),
)
basemap_widget = widgets.HBox([dropdown, close_btn])
def on_click(change):
if change["new"]:
basemap_name = dropdown.value
if basemap_name not in m.get_layer_names():
m.add_basemap(basemap_name)
if basemap_name in xyz_dict:
if "bounds" in xyz_dict[basemap_name]:
bounds = xyz_dict[basemap_name]["bounds"]
bounds = [
bounds[0][1],
bounds[0][0],
bounds[1][1],
bounds[1][0],
]
m.zoom_to_bounds(bounds)
dropdown.observe(on_click, "value")
def close_click(change):
m.toolbar_reset()
if m.basemap_ctrl is not None and m.basemap_ctrl in m.controls:
m.remove_control(m.basemap_ctrl)
basemap_widget.close()
close_btn.on_click(close_click)
basemap_control = ipyleaflet.WidgetControl(
widget=basemap_widget, position="topright"
)
m.add(basemap_control)
m.basemap_ctrl = basemap_control
def convert_js2py(m):
"""A widget for converting Earth Engine JavaScript to Python.
Args:
m (object): geemap.Map
"""
full_widget = widgets.VBox(layout=widgets.Layout(width="465px", height="350px"))
text_widget = widgets.Textarea(
placeholder="Paste your Earth Engine JavaScript into this textbox and click the Convert button below to convert the Javascript to Python",
layout=widgets.Layout(width="455px", height="310px"),
)
buttons = widgets.ToggleButtons(
value=None,
options=["Convert", "Clear", "Close"],
tooltips=["Convert", "Clear", "Close"],
button_style="primary",
)
buttons.style.button_width = "128px"
def button_clicked(change):
if change["new"] == "Convert":
from .conversion import create_new_cell, js_snippet_to_py
if len(text_widget.value) > 0:
out_lines = js_snippet_to_py(
text_widget.value,
add_new_cell=False,
import_ee=False,
import_geemap=False,
show_map=False,
)
if len(out_lines) > 0 and len(out_lines[0].strip()) == 0:
out_lines = out_lines[1:]
prefix = "# The code has been copied to the clipboard. \n# Press Ctrl+V to in a code cell to paste it.\n"
text_widget.value = "".join([prefix] + out_lines)
create_code_cell("".join(out_lines))
elif change["new"] == "Clear":
text_widget.value = ""
elif change["new"] == "Close":
m.toolbar_reset()
if m.convert_ctrl is not None and m.convert_ctrl in m.controls:
m.remove_control(m.convert_ctrl)
full_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
full_widget.children = [text_widget, buttons]
widget_control = ipyleaflet.WidgetControl(widget=full_widget, position="topright")
m.add_control(widget_control)
m.convert_ctrl = widget_control
def collect_samples(m):
full_widget = widgets.VBox()
layout = widgets.Layout(width="100px")
prop_label = widgets.Label(
value="Property",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
value_label = widgets.Label(
value="Value",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
color_label = widgets.Label(
value="Color",
layout=widgets.Layout(display="flex", justify_content="center", width="100px"),
)
prop_text1 = widgets.Text(layout=layout, placeholder="Required")
value_text1 = widgets.Text(layout=layout, placeholder="Integer")
prop_text2 = widgets.Text(layout=layout, placeholder="Optional")
value_text2 = widgets.Text(layout=layout, placeholder="String")
color = widgets.ColorPicker(
concise=False,
value="#3388ff",
layout=layout,
style={"description_width": "initial"},
)
buttons = widgets.ToggleButtons(
value=None,
options=["Apply", "Clear", "Close"],
tooltips=["Apply", "Clear", "Close"],
button_style="primary",
)
buttons.style.button_width = "99px"
def button_clicked(change):
if change["new"] == "Apply":
if len(color.value) != 7:
color.value = "#3388ff"
draw_control = ipyleaflet.DrawControl(
marker={"shapeOptions": {"color": color.value}, "repeatMode": False},
rectangle={"shapeOptions": {"color": color.value}, "repeatMode": False},
polygon={"shapeOptions": {"color": color.value}, "repeatMode": False},
circlemarker={},
polyline={},
edit=False,
remove=False,
)
controls = []
old_draw_control = None
for control in m.controls:
if isinstance(control, ipyleaflet.DrawControl):
controls.append(draw_control)
old_draw_control = control
else:
controls.append(control)
m.controls = tuple(controls)
old_draw_control.close()
m.draw_control = draw_control
train_props = {}
if prop_text1.value != "" and value_text1.value != "":
try:
_ = int(value_text1.value)
except Exception as _:
value_text1.placeholder = "Integer only"
value_text1.value = ""
return
train_props[prop_text1.value] = int(value_text1.value)
if prop_text2.value != "" and value_text2.value != "":
train_props[prop_text2.value] = value_text2.value
if color.value != "":
train_props["color"] = color.value
# Handles draw events
def handle_draw(target, action, geo_json):
from .geemap import ee_tile_layer
try:
geom = geojson_to_ee(geo_json, False)
m.user_roi = geom
if len(train_props) > 0:
feature = ee.Feature(geom, train_props)
else:
feature = ee.Feature(geom)
m.draw_last_json = geo_json
m.draw_last_feature = feature
if action == "deleted" and len(m.draw_features) > 0:
m.draw_features.remove(feature)
m.draw_count -= 1
else:
m.draw_features.append(feature)
m.draw_count += 1
collection = ee.FeatureCollection(m.draw_features)
m.user_rois = collection
ee_draw_layer = ee_tile_layer(
collection, {"color": "blue"}, "Drawn Features", False, 0.5
)
draw_layer_index = m.find_layer_index("Drawn Features")
if draw_layer_index == -1:
m.add_layer(ee_draw_layer)
m.draw_layer = ee_draw_layer
else:
m.substitute_layer(m.draw_layer, ee_draw_layer)
m.draw_layer = ee_draw_layer
except Exception as e:
m.draw_count = 0
m.draw_features = []
m.draw_last_feature = None
m.draw_layer = None
m.user_roi = None
m.roi_start = False
m.roi_end = False
print("There was an error creating Earth Engine Feature.")
raise Exception(e)
draw_control.on_draw(handle_draw)
elif change["new"] == "Clear":
prop_text1.value = ""
value_text1.value = ""
prop_text2.value = ""
value_text2.value = ""
color.value = "#3388ff"
elif change["new"] == "Close":
m.toolbar_reset()
if m.training_ctrl is not None and m.training_ctrl in m.controls:
m.remove_control(m.training_ctrl)
full_widget.close()
buttons.value = None
buttons.observe(button_clicked, "value")
full_widget.children = [
widgets.HBox([prop_label, value_label, color_label]),
widgets.HBox([prop_text1, value_text1, color]),
widgets.HBox([prop_text2, value_text2, color]),
buttons,
]
widget_control = ipyleaflet.WidgetControl(widget=full_widget, position="topright")
m.add_control(widget_control)
m.training_ctrl = widget_control
def get_tools_dict():
import pandas as pd
import pkg_resources
pkg_dir = os.path.dirname(pkg_resources.resource_filename("geemap", "geemap.py"))
toolbox_csv = os.path.join(pkg_dir, "data/template/toolbox.csv")
df = pd.read_csv(toolbox_csv).set_index("index")
tools_dict = df.to_dict("index")
return tools_dict
def tool_gui(tool_dict, max_width="420px", max_height="600px"):
"""Create a GUI for a tool based on the tool dictionary.
Args:
tool_dict (dict): The dictionary containing the tool info.
max_width (str, optional): The max width of the tool dialog.
max_height (str, optional): The max height of the tool dialog.
Returns:
object: An ipywidget object representing the tool interface.
"""
tool_widget = widgets.VBox(
layout=widgets.Layout(max_width=max_width, max_height=max_height)
)
children = []
args = {}
required_inputs = []
style = {"description_width": "initial"}
max_width = str(int(max_width.replace("px", "")) - 10) + "px"
header_width = str(int(max_width.replace("px", "")) - 104) + "px"
header = widgets.Label(
value=f'Current Tool: {tool_dict["label"]}',
style=style,
layout=widgets.Layout(width=header_width),
)
code_btn = widgets.Button(
description="View Code", layout=widgets.Layout(width="100px")
)
children.append(widgets.HBox([header, code_btn]))
desc = widgets.Textarea(
value=f'Description: {tool_dict["description"]}',
layout=widgets.Layout(width="410px", max_width=max_width),
disabled=True,
)
children.append(desc)
run_btn = widgets.Button(description="Run", layout=widgets.Layout(width="100px"))
cancel_btn = widgets.Button(
description="Cancel", layout=widgets.Layout(width="100px")
)
help_btn = widgets.Button(description="Help", layout=widgets.Layout(width="100px"))
import_btn = widgets.Button(
description="Import",
tooltip="Import the script to a new cell",
layout=widgets.Layout(width="98px"),
)
tool_output = widgets.Output(layout=widgets.Layout(max_height="200px"))
children.append(widgets.HBox([run_btn, cancel_btn, help_btn, import_btn]))
children.append(tool_output)
tool_widget.children = children
def run_button_clicked(b):
tool_output.clear_output()
required_params = required_inputs.copy()
args2 = []
for arg in args:
line = ""
if isinstance(args[arg], FileChooser):
if arg in required_params and args[arg].selected is None:
with tool_output:
print(f"Please provide inputs for required parameters.")
break
elif arg in required_params:
required_params.remove(arg)
if arg == "i":
line = f"-{arg}={args[arg].selected}"
else:
line = f"--{arg}={args[arg].selected}"
elif isinstance(args[arg], widgets.Text):
if arg in required_params and len(args[arg].value) == 0:
with tool_output:
print(f"Please provide inputs for required parameters.")
break
elif arg in required_params:
required_params.remove(arg)
if args[arg].value is not None and len(args[arg].value) > 0:
line = f"--{arg}={args[arg].value}"
elif isinstance(args[arg], widgets.Checkbox):
line = f"--{arg}={args[arg].value}"
args2.append(line)
if len(required_params) == 0:
with tool_output: