Skip to content

Commit

Permalink
Improved DrawControl
Browse files Browse the repository at this point in the history
  • Loading branch information
giswqs committed Mar 26, 2020
1 parent 5932098 commit e52d275
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 31 deletions.
66 changes: 53 additions & 13 deletions examples/notebooks/ipyleaflet_draw_control.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,40 @@
"Map"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Draw any shapes on the map above using the Draw Control."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Retrieves ee.Feature() of the last drawing object.\n",
"Map.draw_last_feature"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Retrieves ee.Feature() of all drawing objects.\n",
"Map.draw_features"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Clipping Earth Engine Image layer with the Draw Control "
]
},
{
"cell_type": "code",
"execution_count": null,
Expand All @@ -87,7 +121,10 @@
"source": [
"import ipywidgets as widgets\n",
"from ipyleaflet import WidgetControl\n",
"from geemap import geojson_to_eegeometry\n",
"from geemap import geojson_to_ee\n",
"\n",
"Map = emap.Map(center=[40,-100], zoom=4)\n",
"Map.add_basemap('ROADMAP') # Add \n",
"\n",
"# Add Earth Engine dataset\n",
"image = ee.Image('USGS/SRTMGL1_003')\n",
Expand All @@ -102,7 +139,7 @@
"base_layers = Map.layers\n",
"\n",
"# Add Earth Engine DEM to map\n",
"Map.addLayer(image, vis_params, 'EE DEM')\n",
"Map.addLayer(image, vis_params, 'SRTM DEM')\n",
"\n",
"# An empty list for storing drawing geometries\n",
"feat_list = []\n",
Expand All @@ -113,28 +150,31 @@
"# Handle draw events\n",
"def handle_draw(self, action, geo_json):\n",
"\n",
" geom = geojson_to_eegeometry(geo_json, False)\n",
" geom = geojson_to_ee(geo_json, False)\n",
" feature = ee.Feature(geom)\n",
" feat_list.append(feature)\n",
" collection = ee.FeatureCollection(feat_list)\n",
" clip_image = image.clipToCollection(collection)\n",
" \n",
" Map.layers = base_layers[:3]\n",
" Map.addLayer(clip_image, vis_params, 'EE DEM')\n",
" Map.addLayer(ee.Image().paint(collection, 0, 2), {'palette': 'red'}, 'EE Geometry')\n",
" Map.addLayer(clip_image, vis_params, 'SRTM DEM')\n",
"# Map.addLayer(ee.Image().paint(collection, 0, 2), {'palette': 'red'}, 'EE Geometry')\n",
" Map.addLayer(collection, {}, 'Drawing Features')\n",
"\n",
"dc.on_draw(handle_draw)\n",
"\n",
"# Add a button to the map\n",
"button = widgets.Button(description=\"Clear drawings\")\n",
"btn_control = WidgetControl(widget=button, position='bottomright')\n",
"Map.add_control(btn_control)\n",
"# # Add a button to the map\n",
"# button = widgets.Button(description=\"Clear drawings\")\n",
"# btn_control = WidgetControl(widget=button, position='bottomright')\n",
"# Map.add_control(btn_control)\n",
"\n",
"# Handle click event\n",
"def on_button_clicked(b):\n",
" dc.clear()\n",
"# # Handle click event\n",
"# def on_button_clicked(b):\n",
"# dc.clear()\n",
"\n",
"button.on_click(on_button_clicked)"
"# button.on_click(on_button_clicked)\n",
"\n",
"Map"
]
},
{
Expand Down
2 changes: 1 addition & 1 deletion geemap/eefolium.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def add_layer(self, ee_object, vis_params={}, name='Layer untitled', shown=True,
elif isinstance(ee_object, ee.image.Image):
image = ee_object
elif isinstance(ee_object, ee.imagecollection.ImageCollection):
image = ee_object.median()
image = ee_object.mosaic()

map_id_dict = ee.Image(image).getMapId(vis_params)
folium.raster_layers.TileLayer(
Expand Down
71 changes: 54 additions & 17 deletions geemap/geemap.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,13 @@ class Map(ipyleaflet.Map):
"""
def __init__(self, **kwargs):

# Authenticates Earth Engine and initialize an Earth Engine session
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()

# Default map center location and zoom level
latlon = [40, -100]
zoom = 4
Expand All @@ -137,13 +144,14 @@ def __init__(self, **kwargs):
else:
kwargs['zoom'] = zoom

# Inherit the ipyleaflet Map class
super().__init__(**kwargs)
self.scroll_wheel_zoom= True
self.layout.height = '550px'

layers = LayersControl(position='topright')
self.add_control(layers)
self.layer_control = layers
layer_control = LayersControl(position='topright')
self.add_control(layer_control)
self.layer_control = layer_control

scale =ScaleControl(position='bottomleft')
self.add_control(scale)
Expand All @@ -153,15 +161,6 @@ def __init__(self, **kwargs):
self.add_control(fullscreen)
self.fullscreen_control = fullscreen

draw = DrawControl(marker={'shapeOptions': {'color': '#0000FF'}},
rectangle={'shapeOptions': {'color': '#0000FF'}},
circle={'shapeOptions': {'color': '#0000FF'}},
circlemarker={},
)

self.add_control(draw)
self.draw_control = draw

measure = MeasureControl(
position='bottomleft',
active_color='orange',
Expand All @@ -170,6 +169,41 @@ def __init__(self, **kwargs):
self.add_control(measure)
self.measure_control = measure

draw_control = DrawControl(marker={'shapeOptions': {'color': '#0000FF'}},
rectangle={'shapeOptions': {'color': '#0000FF'}},
circle={'shapeOptions': {'color': '#0000FF'}},
circlemarker={},
)

self.draw_count = 0 # The number of shapes drawn by the user using the DrawControl
self.draw_features = [] # The list of Earth Engine Geometry objects converted from geojson
self.draw_last_feature = None # The Earth Engine Geometry object converted from the last drawn feature

# Handles draw events
def handle_draw(target, action, geo_json):
try:
self.draw_count += 1
geom = geojson_to_ee(geo_json, False)
feature = ee.Feature(geom)
self.draw_last_feature = feature
self.draw_features.append(feature)
collection = ee.FeatureCollection(self.draw_features)

if self.draw_count > 1:
self.layers = self.layers[:-1]

self.addLayer(collection, {'color': 'blue'}, 'Drawing Features', True, 0.5)
draw_control.clear()
except:
print("There was an error creating Earth Engine Feature.")
self.draw_count = 0
self.draw_features = []
self.draw_last_feature = None

draw_control.on_draw(handle_draw)
self.add_control(draw_control)
self.draw_control = draw_control

# Adds Inspector widget
checkbox = widgets.Checkbox(
value=False,
Expand Down Expand Up @@ -602,7 +636,7 @@ def ee_tile_layer(ee_object, vis_params={}, name='Layer untitled', shown=True, o
return tile_layer


def geojson_to_eegeometry(geo_json, geodesic=True):
def geojson_to_ee(geo_json, geodesic=True):
"""Converts a geojson to ee.Geometry()
Args:
Expand All @@ -612,16 +646,19 @@ def geojson_to_eegeometry(geo_json, geodesic=True):
ee_object: An ee.Geometry object
"""
try:

geom = None
keys = geo_json['properties']['style'].keys()
if 'radius' in keys:
if 'radius' in keys: # Checks whether it is a circle
geom = ee.Geometry(geo_json['geometry'])
radius = geo_json['properties']['style']['radius']
geom = geom.buffer(radius)
# return geom
elif geo_json['geometry']['type'] == 'Point': # Checks whether it is a point
coordinates = geo_json['geometry']['coordinates']
longitude = coordinates[0]
latitude = coordinates[1]
geom = ee.Geometry.Point(longitude, latitude)
else:
geom = ee.Geometry(geo_json['geometry'], "", geodesic)
# if 'radius' in keys: # Checks whether it is a circle
return geom

except:
Expand Down

0 comments on commit e52d275

Please sign in to comment.