Clip Earth Engine images interactively with the Draw Control
Uncomment the following line to install geemap if needed.
# %pip install -U geemap
import ee
import geemap
import ipywidgets as widgets
Add some Earth Engine data to the map, then you can use the draw control and a button widget to clip the Earth Engine data by the drawn polygons.
The drawn geometries can be retrieved as either an ee.Geometry object (m.user_roi
) or ee.FeatureCollection (m._user_rois
).
self = geemap.Map(center=[0, 9.31], zoom=3)
image = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 6000,
"palette": "terrain",
}
self.add_layer(image, vis_params, "SRTM")
clip_btn = widgets.Button(description="Clip Image")
reset_btn = widgets.Button(description="Reset")
def on_clip_btn_clicked(b):
if self.user_roi is not None:
try:
clipped_image = image.clip(self.user_roi)
self.add_layer(clipped_image, vis_params, "Clipped Image")
self.find_layer("SRTM").visible = False
except:
pass
clip_btn.on_click(on_clip_btn_clicked)
def on_reset_btn_clicked(b):
self._draw_control.clear()
self.find_layer("SRTM").visible = True
self.layers = self.layers[:3]
reset_btn.on_click(on_reset_btn_clicked)
widget = widgets.VBox([clip_btn, reset_btn])
self.add_widget(widget, position="bottomright")
self
Create a solara web app.
import ee
import geemap
import solara
import ipywidgets as widgets
class Map(geemap.Map):
def __init__(self, **kwargs):
super().__init__(**kwargs)
image = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 6000,
"palette": "terrain",
}
self.add_layer(image, vis_params, "SRTM")
clip_btn = widgets.Button(description="Clip Image")
reset_btn = widgets.Button(description="Reset")
def on_clip_btn_clicked(b):
if self.user_roi is not None:
try:
clipped_image = image.clip(self.user_roi)
self.add_layer(clipped_image, vis_params, "Clipped Image")
self.find_layer("SRTM").visible = False
except:
pass
clip_btn.on_click(on_clip_btn_clicked)
def on_reset_btn_clicked(b):
self._draw_control.clear()
self.find_layer("SRTM").visible = True
self.layers = self.layers[:3]
reset_btn.on_click(on_reset_btn_clicked)
widget = widgets.VBox([clip_btn, reset_btn])
self.add_widget(widget, position="bottomright")
@solara.component
def Page():
with solara.Column(style={"min-width": "500px"}):
Map.element(
center=[0, 9.31],
zoom=3,
height="600px",
)
Page()