Install the Earth Engine Python API and geemap. The geemap Python package is built upon the ipyleaflet and folium packages and implements several methods for interacting with Earth Engine data layers, such as Map.addLayer()
, Map.setCenter()
, and Map.centerObject()
.
The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its dependencies, including earthengine-api, folium, and ipyleaflet.
Important note: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only (source). Note that Google Colab currently does not support ipyleaflet (source). Therefore, if you are using geemap with Google Colab, you should use import geemap.eefolium
. If you are using geemap with binder or a local Jupyter notebook server, you can use import geemap
, which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).
# Installs geemap package
import subprocess
try:
import geemap
except ImportError:
print('geemap package not installed. Installing ...')
subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap'])
# Checks whether this notebook is running on Google Colab
try:
import google.colab
import geemap.eefolium as emap
except:
import geemap as emap
# Authenticates and initializes Earth Engine
import ee
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
Map = emap.Map(center=(40, -100), zoom=4)
Map
# Add Earth Engine dataset
image = ee.Image('USGS/SRTMGL1_003')
# Set visualization parameters.
vis_params = {
'min': 0,
'max': 4000,
'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}
# Print the elevation of Mount Everest.
xy = ee.Geometry.Point([86.9250, 27.9881])
elev = image.sample(xy, 30).first().get('elevation').getInfo()
print('Mount Everest elevation (m):', elev)
# Add Earth Engine layers to Map
Map.addLayer(image, vis_params, 'SRTM DEM', True, 0.5)
Map.addLayer(xy, {'color': 'red'}, 'Mount Everest')
For example, center the map on an Earth Engine object:
Map.centerObject(ee_object=xy, zoom=13)
Set the map center using coordinates (longitude, latitude)
Map.setCenter(lon=-100, lat=40, zoom=4)
import ee
import geemap
from ipyleaflet import *
from ipywidgets import Label
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
Map = geemap.Map(center=(40, -100), zoom=4)
Map.default_style = {'cursor': 'crosshair'}
# Add Earth Engine dataset
image = ee.Image('USGS/SRTMGL1_003')
# Set visualization parameters.
vis_params = {
'min': 0,
'max': 4000,
'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5']}
# Add Earth Eninge layers to Map
Map.addLayer(image, vis_params, 'STRM DEM', True, 0.5)
latlon_label = Label()
elev_label = Label()
display(latlon_label)
display(elev_label)
coordinates = []
markers = []
marker_cluster = MarkerCluster(name="Marker Cluster")
Map.add_layer(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get('coordinates')
if kwargs.get('type') == 'mousemove':
latlon_label.value = "Coordinates: {}".format(str(latlon))
elif kwargs.get('type') == 'click':
coordinates.append(latlon)
# Map.add_layer(Marker(location=latlon))
markers.append(Marker(location=latlon))
marker_cluster.markers = markers
xy = ee.Geometry.Point(latlon[::-1])
elev = image.sample(xy, 30).first().get('elevation').getInfo()
elev_label.value = "Elevation of {}: {} m".format(latlon, elev)
Map.on_interaction(handle_interaction)
Map
import ee
import geemap
from ipyleaflet import *
from bqplot import pyplot as plt
try:
ee.Initialize()
except Exception as e:
ee.Authenticate()
ee.Initialize()
Map = geemap.Map(center=(40, -100), zoom=4)
Map.default_style = {'cursor': 'crosshair'}
# Compute the trend of nighttime lights from DMSP.
# Add a band containing image date as years since 1990.
def createTimeBand(img):
year = img.date().difference(ee.Date('1991-01-01'), 'year')
return ee.Image(year).float().addBands(img)
NTL = ee.ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS') \
.select('stable_lights')
# Fit a linear trend to the nighttime lights collection.
collection = NTL.map(createTimeBand)
fit = collection.reduce(ee.Reducer.linearFit())
image = NTL.toBands()
figure = plt.figure(1, title='Nighttime Light Trend', layout={'max_height': '250px', 'max_width': '400px'})
count = collection.size().getInfo()
start_year = 1992
end_year = 2013
x = range(1, count+1)
coordinates = []
markers = []
marker_cluster = MarkerCluster(name="Marker Cluster")
Map.add_layer(marker_cluster)
def handle_interaction(**kwargs):
latlon = kwargs.get('coordinates')
if kwargs.get('type') == 'click':
coordinates.append(latlon)
markers.append(Marker(location=latlon))
marker_cluster.markers = markers
xy = ee.Geometry.Point(latlon[::-1])
y = image.sample(xy, 500).first().toDictionary().values().getInfo()
plt.clear()
plt.plot(x, y)
# plt.xticks(range(start_year, end_year, 5))
Map.on_interaction(handle_interaction)
# Display a single image
Map.addLayer(ee.Image(collection.select('stable_lights').first()), {'min': 0, 'max': 63}, 'First image')
# Display trend in red/blue, brightness in green.
Map.setCenter(30, 45, 4)
Map.addLayer(fit,
{'min': 0, 'max': [0.18, 20, -0.18], 'bands': ['scale', 'offset', 'scale']},
'stable lights trend')
fig_control = WidgetControl(widget=figure, position='bottomright')
Map.add_control(fig_control)
Map