Intro to Earth Engine in Python
This notebook contains the materials for the workshop Intro to Earth Engine in Python at the 2024 Indiana Geographic Information Council (IGIC) Annual Conference.
This workshop provides an introduction to cloud-based geospatial analysis using the Earth Engine Python API. Attendees will learn the basics of Earth Engine data types and how to visualize, analyze, and export Earth Engine data in a Jupyter environment with geemap. In addition, attendees will learn how to develop and deploy interactive Earth Engine web apps with Python. Through practical examples and hands-on exercises, attendees will enhance their learning experience. It is recommended that attendees have a basic understanding of Python and Jupyter Notebook. Familiarity with the Earth Engine JavaScript API is not required but will be helpful. Attendees can use Google Colab to follow this workshop without installing anything on their computer.
The workshop is divided into three parts.
The first part will cover the following topics:
The second part will cover the following topics:
The third part will cover the following topics:
Google Earth Engine is a cloud-computing platform for scientific analysis and visualization of geospatial datasets. It is free for noncommercial and research use. For more than a decade, Earth Engine has enabled planetary-scale Earth data science and analysis by nonprofit organizations, research scientists, and other impact users.
With the launch of Earth Engine for commercial use, commercial customers will be charged for Earth Engine services. However, Earth Engine will remain free of charge for noncommercial use and research projects. Nonprofit organizations, academic institutions, educators, news media, Indigenous governments, and government researchers are eligible to use Earth Engine free of charge, just as they have done for over a decade.
Currently, ipywidgets does not work well with Colab dark theme. Some of the geemap widgets may not display properly in Colab dark theme.It is recommended that you change Colab to the light theme.
The geemap package is pre-installed in Google Colab and is updated to the latest minor or major release every few weeks. Some optional dependencies of geemap being used by this notebook are not pre-installed in Colab. Uncomment the following line to install geemap and some optional dependencies.
# %pip install -U "geemap[workshop]" cartopy solara flask==2.3.3
Note that some geemap features do not work properly with Google Colab. If you are familiar with Anaconda or Miniconda, it is recommended to create a new conda environment to install geemap and its optional dependencies on your local computer.
conda create -n gee python=3.11
conda activate gee
conda install -c conda-forge mamba
mamba install -c conda-forge geemap pygis cartopy solara flask==2.3.3
Import the earthengine-api and geemap.
import ee
import geemap
You will need to create a Google Cloud Project and enable the Earth Engine API for the project. You can find detailed instructions here.
geemap.ee_initialize()
Let's create an interactive map using the ipyleaflet
plotting backend. The geemap.Map
class inherits the ipyleaflet.Map
class. Therefore, you can use the same syntax to create an interactive map as you would with ipyleaflet.Map
.
m = geemap.Map()
To display it in a Jupyter notebook, simply ask for the object representation:
m
To customize the map, you can specify various keyword arguments, such as center
([lat, lon]), zoom
, width
, and height
. The default width
is 100%
, which takes up the entire cell width of the Jupyter notebook. The height
argument accepts a number or a string. If a number is provided, it represents the height of the map in pixels. If a string is provided, the string must be in the format of a number followed by px
, e.g., 600px
.
Generate a map that focuses on the contiguous United States.
m = geemap.Map(center=[40, -100], zoom=4)
m
Generate a map that focuses on Indiana.
m = geemap.Map(center=[39.814613, -86.117887], zoom=7)
m
Generate a map that focuses on Michigan City, IN.
m = geemap.Map(center=[41.701756, -86.895448], zoom=13)
m
To hide a control, set control_name
to False
, e.g., draw_ctrl=False
.
m = geemap.Map(data_ctrl=False, toolbar_ctrl=False, draw_ctrl=False)
m
There are several ways to add basemaps to a map. You can specify the basemap to use in the basemap
keyword argument when creating the map. Alternatively, you can add basemap layers to the map using the add_basemap
method. Geemap has hundreds of built-in basemaps available that can be easily added to the map with only one line of code.
Create a map by specifying the basemap to use as follows. For example, the Esri.WorldImagery
basemap represents the Esri world imagery basemap.
m = geemap.Map(basemap="Esri.WorldImagery")
m
You can add as many basemaps as you like to the map. For example, the following code adds the OpenTopoMap
basemap to the map above:
m.add_basemap("Esri.WorldTopoMap")
m.add_basemap("OpenTopoMap")
Print out the first 10 basemaps:
basemaps = list(geemap.basemaps.keys())
len(geemap.basemaps)
basemaps[:10]
You can also change basemaps interactively using the basemap GUI.
Google basemaps are not included in the geemap built-in basemaps due to license issues (source). Users can choose to add Google basemaps at their own risks as follows:
ROADMAP: https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}
SATELLITE: https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}
TERRAIN: https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}
HYBRID: https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}
m = geemap.Map()
url = "https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}"
m.add_tile_layer(url, name="Google Satellite", attribution="Google")
m
geemap.
in the code cell.
ee.
in the code cell.
m = geemap.Map()
m.add("basemap_selector")
m
Toggle the checkbox to show or hide the layer. Drag and move the slider to change the transparency level of the layer.
m = geemap.Map(center=(40, -100), zoom=4)
dem = ee.Image("USGS/SRTMGL1_003")
states = ee.FeatureCollection("TIGER/2018/States")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(dem, vis_params, "SRTM DEM")
m.add_layer(states, {}, "US States")
m.add("layer_manager")
m
Click on the map to query Earth Engine data at a specific location.
m = geemap.Map(center=(40, -100), zoom=4)
dem = ee.Image("USGS/SRTMGL1_003")
landsat7 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003")
states = ee.FeatureCollection("TIGER/2018/States")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(dem, vis_params, "SRTM DEM")
m.add_layer(
landsat7,
{"bands": ["B4", "B3", "B2"], "min": 20, "max": 200, "gamma": 2.0},
"Landsat 7",
)
m.add_layer(states, {}, "US States")
m.add("inspector")
m
m = geemap.Map(center=(40, -100), zoom=4)
dem = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(dem, vis_params, "SRTM DEM")
m.add("layer_editor", layer_dict=m.ee_layers["SRTM DEM"])
m
m = geemap.Map(center=(40, -100), zoom=4)
landsat7 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003")
m.add_layer(
landsat7,
{"bands": ["B4", "B3", "B2"], "min": 20, "max": 200, "gamma": 2.0},
"Landsat 7",
)
m.add("layer_editor", layer_dict=m.ee_layers["Landsat 7"])
m
m = geemap.Map(center=(40, -100), zoom=4)
states = ee.FeatureCollection("TIGER/2018/States")
m.add_layer(states, {}, "US States")
m.add("layer_editor", layer_dict=m.ee_layers["US States"])
m
You can draw shapes on the map using the draw control. The drawn features will be automatically converted to Earth Engine objects, which can be accessed in one of the following ways:
ee.Geometry()
, use: m.user_roi
ee.FeatureCollection()
, use: m.user_rois
m = geemap.Map(center=(40, -100), zoom=4)
dem = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 4000,
"palette": "terrain",
}
m.add_layer(dem, vis_params, "SRTM DEM")
m.add("layer_manager")
m
if m.user_roi is not None:
image = dem.clip(m.user_roi)
m.layers[1].visible = False
m.add_layer(image, vis_params, "Clipped DEM")
The Earth Engine Data Catalog hosts a variety of geospatial datasets. As of March 2024, the catalog contains over 1,100 datasets with a total size of over 100 petabytes. Some notable datasets include: Landsat, Sentinel, MODIS, NAIP, etc. For a complete list of datasets in CSV or JSON formats, see the Earth Engine Datasets List.
The Earth Engine Data Catalog is searchable. You can search datasets by name, keyword, or tag. For example, enter "elevation" in the search box will filter the catalog to show only datasets containing "elevation" in their name, description, or tags. 52 datasets are returned for this search query. Scroll down the list to find the NASA SRTM Digital Elevation 30m dataset. On each dataset page, you can find the following information, including Dataset Availability, Dataset Provider, Earth Engine Snippet, Tags, Description, Code Example, and more. One important piece of information is the Image/ImageCollection/FeatureCollection ID of each dataset, which is essential for accessing the dataset through the Earth Engine JavaScript or Python APIs.
m = geemap.Map()
m
from geemap.datasets import DATA
m = geemap.Map()
dataset = ee.Image(DATA.USGS_GAP_AK_2001)
m.add_layer(dataset, {}, "GAP Alaska")
m.centerObject(dataset, zoom=4)
m
from geemap.datasets import get_metadata
get_metadata(DATA.USGS_GAP_AK_2001)
Earth Engine objects are server-side objects rather than client-side objects, which means that they are not stored locally on your computer. Similar to video streaming services (e.g., YouTube, Netflix, and Hulu), which store videos/movies on their servers, Earth Engine data are stored on the Earth Engine servers. We can stream geospatial data from Earth Engine on-the-fly without having to download the data just like we can watch videos from streaming services using a web browser without having to download the entire video to your computer.
Raster data in Earth Engine are represented as Image objects. Images are composed of one or more bands and each band has its own name, data type, scale, mask and projection. Each image has metadata stored as a set of properties.
Images can be loaded by passing an Earth Engine asset ID into the ee.Image
constructor. You can find image IDs in the Earth Engine Data Catalog. For example, to load the NASA SRTM Digital Elevation you can use:
image = ee.Image("USGS/SRTMGL1_003")
image
m = geemap.Map(center=[21.79, 70.87], zoom=3)
image = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 6000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"], # 'terrain'
}
m.add_layer(image, vis_params, "SRTM")
m
An ImageCollection
is a stack or sequence of images. An ImageCollection
can be loaded by passing an Earth Engine asset ID into the ImageCollection
constructor. You can find ImageCollection
IDs in the Earth Engine Data Catalog.
For example, to load the image collection of the Sentinel-2 surface reflectance:
collection = ee.ImageCollection("COPERNICUS/S2_SR")
Let's find out how many Sentinel-2 images covering Blue Chip Casino Hotel Spa.
geometry = ee.Geometry.Point([-86.893044, 41.718642])
images = collection.filterBounds(geometry)
images.size()
images.first()
images = (
collection.filterBounds(geometry)
.filterDate("2023-07-01", "2023-09-01")
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 5))
)
images.size()
m = geemap.Map()
image = images.first()
vis = {
"min": 0.0,
"max": 3000,
"bands": ["B4", "B3", "B2"],
}
m.add_layer(image, vis, "Sentinel-2")
m.centerObject(image, 8)
m
To visualize an Earth Engine ImageCollection, we need to convert an ImageCollection to an Image by compositing all the images in the collection to a single image representing, for example, the min, max, median, mean or standard deviation of the images. For example, to create a median value image from a collection, use the collection.median()
method. Let's create a median image from the Sentinel-2 surface reflectance collection:
m = geemap.Map()
image = images.median()
vis = {
"min": 0.0,
"max": 3000,
"bands": ["B8", "B4", "B3"],
}
m.add_layer(image, vis, "Sentinel-2")
m.centerObject(geometry, 8)
m
A FeatureCollection is a collection of Features. A FeatureCollection is analogous to a GeoJSON FeatureCollection object, i.e., a collection of features with associated properties/attributes. Data contained in a shapefile can be represented as a FeatureCollection.
The Earth Engine Data Catalog hosts a variety of vector datasets (e.g,, US Census data, country boundaries, and more) as feature collections. You can find feature collection IDs by searching the data catalog. For example, to load the TIGER roads data by the U.S. Census Bureau:
m = geemap.Map()
fc = ee.FeatureCollection("TIGER/2016/Roads")
m.set_center(-86.894547, 41.718934, 12)
m.add_layer(fc, {}, "Census roads")
m
m = geemap.Map()
states = ee.FeatureCollection("TIGER/2018/States")
fc = states.filter(ee.Filter.eq("NAME", "Indiana"))
m.add_layer(fc, {}, "Indiana")
m.center_object(fc, 7)
m
feat = fc.first()
feat.toDictionary()
geemap.ee_to_df(fc)
m = geemap.Map()
states = ee.FeatureCollection("TIGER/2018/States")
fc = states.filter(ee.Filter.inList("NAME", ["California", "Oregon", "Washington"]))
m.add_layer(fc, {}, "West Coast")
m.center_object(fc, 5)
m
region = m.user_roi
if region is None:
region = ee.Geometry.BBox(-88.40, 29.88, -77.90, 35.39)
fc = ee.FeatureCollection("TIGER/2018/States").filterBounds(region)
m.add_layer(fc, {}, "Southeastern U.S.")
m.center_object(fc, 6)
m = geemap.Map(center=[40, -100], zoom=4)
states = ee.FeatureCollection("TIGER/2018/States")
m.add_layer(states, {}, "US States")
m
m = geemap.Map(center=[40, -100], zoom=4)
states = ee.FeatureCollection("TIGER/2018/States")
style = {"color": "0000ffff", "width": 2, "lineType": "solid", "fillColor": "FF000080"}
m.add_layer(states.style(**style), {}, "US States")
m
m = geemap.Map(center=[40, -100], zoom=4)
states = ee.FeatureCollection("TIGER/2018/States")
vis_params = {
"color": "000000",
"colorOpacity": 1,
"pointSize": 3,
"pointShape": "circle",
"width": 2,
"lineType": "solid",
"fillColorOpacity": 0.66,
}
palette = ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"]
m.add_styled_vector(
states, column="NAME", palette=palette, layer_name="Styled vector", **vis_params
)
m
Create a cloud-free imagery for the state of Indiana. You can use Landsat 8/9 or Sentinel-2 imagery. Relevant Earth Engine assets:
m = geemap.Map(center=[40, -100], zoom=4)
landsat7 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003").select(
["B1", "B2", "B3", "B4", "B5", "B7"]
)
landsat_vis = {"bands": ["B4", "B3", "B2"], "gamma": 1.4}
m.add_layer(landsat7, landsat_vis, "Landsat")
hyperion = ee.ImageCollection("EO1/HYPERION").filter(
ee.Filter.date("2016-01-01", "2017-03-01")
)
hyperion_vis = {
"min": 1000.0,
"max": 14000.0,
"gamma": 2.5,
}
m.add_layer(hyperion, hyperion_vis, "Hyperion")
m.add_plot_gui()
m
Set plotting options for Landsat.
m.set_plot_options(add_marker_cluster=True, overlay=True)
Set plotting options for Hyperion.
m.set_plot_options(add_marker_cluster=True, plot_type="bar")
from geemap.legends import builtin_legends
for legend in builtin_legends:
print(legend)
Add NLCD WMS layer and legend to the map.
m = geemap.Map(center=[40, -100], zoom=4)
m.add_basemap("Esri.WorldImagery")
m.add_basemap("NLCD 2021 CONUS Land Cover")
m.add_legend(builtin_legend="NLCD", max_width="100px", height="455px")
m
Add NLCD Earth Engine layer and legend to the map.
m = geemap.Map(center=[40, -100], zoom=4)
m.add_basemap("Esri.WorldImagery")
nlcd = ee.Image("USGS/NLCD_RELEASES/2021_REL/NLCD/2021")
landcover = nlcd.select("landcover")
m.add_layer(landcover, {}, "NLCD Land Cover 2021")
m.add_legend(
title="NLCD Land Cover Classification", builtin_legend="NLCD", height="455px"
)
m
Add a custom legend by specifying the colors and labels.
m = geemap.Map(add_google_map=False)
keys = ["One", "Two", "Three", "Four", "etc"]
# colors can be defined using either hex code or RGB (0-255, 0-255, 0-255)
colors = ["#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3"]
# legend_colors = [(255, 0, 0), (127, 255, 0), (127, 18, 25), (36, 70, 180), (96, 68 123)]
m.add_legend(keys=keys, colors=colors, position="bottomright")
m
Add a custom legend by specifying a dictionary of colors and labels.
m = geemap.Map(center=[40, -100], zoom=4)
m.add_basemap("Esri.WorldImagery")
legend_dict = {
"11 Open Water": "466b9f",
"12 Perennial Ice/Snow": "d1def8",
"21 Developed, Open Space": "dec5c5",
"22 Developed, Low Intensity": "d99282",
"23 Developed, Medium Intensity": "eb0000",
"24 Developed High Intensity": "ab0000",
"31 Barren Land (Rock/Sand/Clay)": "b3ac9f",
"41 Deciduous Forest": "68ab5f",
"42 Evergreen Forest": "1c5f2c",
"43 Mixed Forest": "b5c58f",
"51 Dwarf Scrub": "af963c",
"52 Shrub/Scrub": "ccb879",
"71 Grassland/Herbaceous": "dfdfc2",
"72 Sedge/Herbaceous": "d1d182",
"73 Lichens": "a3cc51",
"74 Moss": "82ba9e",
"81 Pasture/Hay": "dcd939",
"82 Cultivated Crops": "ab6c28",
"90 Woody Wetlands": "b8d9eb",
"95 Emergent Herbaceous Wetlands": "6c9fb8",
}
nlcd = ee.Image("USGS/NLCD_RELEASES/2021_REL/NLCD/2021")
landcover = nlcd.select("landcover")
m.add_layer(landcover, {}, "NLCD Land Cover 2021")
m.add_legend(title="NLCD Land Cover Classification", legend_dict=legend_dict)
m
Add a horizontal color bar.
m = geemap.Map()
dem = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(dem, vis_params, "SRTM DEM")
m.add_colorbar(vis_params, label="Elevation (m)", layer_name="SRTM DEM")
m
Add a vertical color bar.
m.add_colorbar(
vis_params,
label="Elevation (m)",
layer_name="SRTM DEM",
orientation="vertical",
max_width="100px",
)
Make the color bar background transparent.
m.add_colorbar(
vis_params,
label="Elevation (m)",
layer_name="SRTM DEM",
orientation="vertical",
max_width="100px",
transparent_bg=True,
)
Create a split map with basemaps. Note that ipyleaflet has a bug with the SplitControl. You can't pan the map, which should be resolved in the next ipyleaflet release.
m = geemap.Map()
m.split_map(left_layer="Esri.WorldTopoMap", right_layer="OpenTopoMap")
m
Create a split map with Earth Engine layers.
m = geemap.Map(center=(40, -100), zoom=4, height=600)
nlcd_2001 = ee.Image("USGS/NLCD_RELEASES/2019_REL/NLCD/2001").select("landcover")
nlcd_2021 = ee.Image("USGS/NLCD_RELEASES/2021_REL/NLCD/2021").select("landcover")
left_layer = geemap.ee_tile_layer(nlcd_2001, {}, "NLCD 2001")
right_layer = geemap.ee_tile_layer(nlcd_2021, {}, "NLCD 2021")
m.split_map(left_layer, right_layer)
m
Create a 2x2 linked map for visualizing Sentinel-2 imagery with different band combinations. Note that this feature does not work properly with Colab. Panning one map would not pan other maps.
image = (
ee.ImageCollection("COPERNICUS/S2")
.filterDate("2023-07-01", "2023-09-01")
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", 5))
.map(lambda img: img.divide(10000))
.median()
)
vis_params = [
{"bands": ["B4", "B3", "B2"], "min": 0, "max": 0.3, "gamma": 1.3},
{"bands": ["B8", "B11", "B4"], "min": 0, "max": 0.3, "gamma": 1.3},
{"bands": ["B8", "B4", "B3"], "min": 0, "max": 0.3, "gamma": 1.3},
{"bands": ["B12", "B12", "B4"], "min": 0, "max": 0.3, "gamma": 1.3},
]
labels = [
"Natural Color (B4/B3/B2)",
"Land/Water (B8/B11/B4)",
"Color Infrared (B8/B4/B3)",
"Vegetation (B12/B11/B4)",
]
geemap.linked_maps(
rows=2,
cols=2,
height="300px",
center=[41.718934, -86.894547],
zoom=12,
ee_objects=[image],
vis_params=vis_params,
labels=labels,
label_position="topright",
)
Check the available years of NLCD.
m = geemap.Map(center=[40, -100], zoom=4)
collection = ee.ImageCollection("USGS/NLCD_RELEASES/2019_REL/NLCD").select("landcover")
vis_params = {"bands": ["landcover"]}
years = collection.aggregate_array("system:index").getInfo()
years
Create a timeseries inspector for NLCD. Note that ipyleaflet has a bug with the SplitControl. You can't pan the map, which should be resolved in the next ipyleaflet release.
m.ts_inspector(
left_ts=collection,
right_ts=collection,
left_names=years,
right_names=years,
left_vis=vis_params,
right_vis=vis_params,
width="80px",
)
m
Note that this feature may not work properly with Colab. Restart Colab runtime if the time slider does not work.
Create a map for visualizing MODIS vegetation data.
m = geemap.Map()
collection = (
ee.ImageCollection("MODIS/MCD43A4_006_NDVI")
.filter(ee.Filter.date("2018-06-01", "2018-07-01"))
.select("NDVI")
)
vis_params = {
"min": 0.0,
"max": 1.0,
"palette": "ndvi",
}
m.add_time_slider(collection, vis_params, time_interval=2)
m
Create a map for visualizing weather data.
m = geemap.Map()
collection = (
ee.ImageCollection("NOAA/GFS0P25")
.filterDate("2018-12-22", "2018-12-23")
.limit(24)
.select("temperature_2m_above_ground")
)
vis_params = {
"min": -40.0,
"max": 35.0,
"palette": ["blue", "purple", "cyan", "green", "yellow", "red"],
}
labels = [str(n).zfill(2) + ":00" for n in range(0, 24)]
m.add_time_slider(collection, vis_params, labels=labels, time_interval=1, opacity=0.8)
m
Visualizing Sentinel-2 imagery
m = geemap.Map()
collection = (
ee.ImageCollection("COPERNICUS/S2_SR")
.filterBounds(ee.Geometry.Point([-86.894547, 41.718934]))
.filterMetadata("CLOUDY_PIXEL_PERCENTAGE", "less_than", 10)
.filter(ee.Filter.calendarRange(6, 8, "month"))
)
vis_params = {"min": 0, "max": 4000, "bands": ["B8", "B4", "B3"]}
m.add_time_slider(collection, vis_params)
m.set_center(-86.894547, 41.718934, 12)
m
Create a split map for visualizing the ESA WorldCover for the state of Alaska, with the Esri.WorldImagery
as the left layer, and the ESA WorldCover as the right layer. Add the ESA land cover legend to the map. Relevant Earth Engine assets:
in_geojson = "https://github.com/gee-community/geemap/blob/master/examples/data/countries.geojson"
m = geemap.Map()
fc = geemap.geojson_to_ee(in_geojson)
m.add_layer(fc.style(**{"color": "ff0000", "fillColor": "00000000"}), {}, "Countries")
m
url = "https://github.com/gee-community/geemap/blob/master/examples/data/countries.zip"
geemap.download_file(url, overwrite=True)
in_shp = "countries.shp"
fc = geemap.shp_to_ee(in_shp)
m = geemap.Map()
m.add_layer(fc, {}, "Countries")
m
import geopandas as gpd
gdf = gpd.read_file(in_shp)
fc = geemap.gdf_to_ee(gdf)
m = geemap.Map()
m.add_layer(fc, {}, "Countries")
m
m = geemap.Map()
states = ee.FeatureCollection("TIGER/2018/States")
fc = states.filter(ee.Filter.eq("NAME", "Indiana"))
m.add_layer(fc, {}, "Indiana")
m.center_object(fc, 7)
m
geemap.ee_to_geojson(fc, filename="Indiana.geojson")
geemap.ee_to_shp(fc, filename="Indiana.shp")
gdf = geemap.ee_to_gdf(fc)
gdf
gdf.explore()
df = geemap.ee_to_df(fc)
df
geemap.ee_to_csv(fc, filename="Indiana.csv")
m = geemap.Map(center=[40, -100], zoom=4)
dem = ee.Image("USGS/SRTMGL1_003")
landsat7 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(
landsat7,
{"bands": ["B4", "B3", "B2"], "min": 20, "max": 200, "gamma": 2},
"Landsat 7",
)
m.add_layer(dem, vis_params, "SRTM DEM", True, 1)
m
in_shp = "us_cities.shp"
url = "https://github.com/giswqs/data/raw/main/us/us_cities.zip"
geemap.download_file(url)
in_fc = geemap.shp_to_ee(in_shp)
m.add_layer(in_fc, {}, "Cities")
geemap.extract_values_to_points(in_fc, dem, out_fc="dem.shp")
geemap.shp_to_gdf("dem.shp")
geemap.extract_values_to_points(in_fc, landsat7, "landsat.csv")
geemap.csv_to_df("landsat.csv")
m = geemap.Map(center=[40, -100], zoom=4)
m.add_basemap("TERRAIN")
image = ee.Image("USGS/SRTMGL1_003")
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(image, vis_params, "SRTM DEM", True, 0.5)
m
line = m.user_roi
if line is None:
line = ee.Geometry.LineString(
[[-120.2232, 36.3148], [-118.9269, 36.7121], [-117.2022, 36.7562]]
)
m.add_layer(line, {}, "ROI")
m.centerObject(line)
reducer = "mean"
transect = geemap.extract_transect(
image, line, n_segments=100, reducer=reducer, to_pandas=True
)
transect
geemap.line_chart(
data=transect,
x="distance",
y="mean",
markers=True,
x_label="Distance (m)",
y_label="Elevation (m)",
height=400,
)
transect.to_csv("transect.csv")
m = geemap.Map(center=[40, -100], zoom=4)
# Add NASA SRTM
dem = ee.Image("USGS/SRTMGL1_003")
dem_vis = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(dem, dem_vis, "SRTM DEM")
# Add 5-year Landsat TOA composite
landsat = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003")
landsat_vis = {"bands": ["B4", "B3", "B2"], "gamma": 1.4}
m.add_layer(landsat, landsat_vis, "Landsat", False)
# Add US Census States
states = ee.FeatureCollection("TIGER/2018/States")
style = {"fillColor": "00000000"}
m.add_layer(states.style(**style), {}, "US States")
m
out_dem_stats = "dem_stats.csv"
geemap.zonal_stats(
dem, states, out_dem_stats, statistics_type="MEAN", scale=1000, return_fc=False
)
out_landsat_stats = "landsat_stats.csv"
geemap.zonal_stats(
landsat,
states,
out_landsat_stats,
statistics_type="MEAN",
scale=1000,
return_fc=False,
)
m = geemap.Map(center=[40, -100], zoom=4)
# Add NLCD data
dataset = ee.Image("USGS/NLCD_RELEASES/2019_REL/NLCD/2019")
landcover = dataset.select("landcover")
m.add_layer(landcover, {}, "NLCD 2019")
# Add US census states
states = ee.FeatureCollection("TIGER/2018/States")
style = {"fillColor": "00000000"}
m.add_layer(states.style(**style), {}, "US States")
# Add NLCD legend
m.add_legend(title="NLCD Land Cover", builtin_legend="NLCD")
m
nlcd_stats = "nlcd_stats.csv"
geemap.zonal_stats_by_group(
landcover,
states,
nlcd_stats,
statistics_type="SUM",
denominator=1e6,
decimal_places=2,
)
nlcd_stats = "nlcd_stats_pct.csv"
geemap.zonal_stats_by_group(
landcover,
states,
nlcd_stats,
statistics_type="PERCENTAGE",
denominator=1e6,
decimal_places=2,
)
m = geemap.Map(center=[40, -100], zoom=4)
dem = ee.Image("USGS/3DEP/10m")
vis = {"min": 0, "max": 4000, "palette": "terrain"}
m.add_layer(dem, vis, "DEM")
m
landcover = ee.Image("USGS/NLCD_RELEASES/2019_REL/NLCD/2019").select("landcover")
m.add_layer(landcover, {}, "NLCD 2019")
m.add_legend(title="NLCD Land Cover Classification", builtin_legend="NLCD")
stats = geemap.image_stats_by_zone(dem, landcover, reducer="MEAN")
stats
stats.to_csv("mean.csv", index=False)
geemap.image_stats_by_zone(dem, landcover, out_csv="std.csv", reducer="STD")
m = geemap.Map()
# Load a 5-year Landsat 7 composite 1999-2003.
landsat_1999 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003")
# Compute NDVI.
ndvi_1999 = (
landsat_1999.select("B4")
.subtract(landsat_1999.select("B3"))
.divide(landsat_1999.select("B4").add(landsat_1999.select("B3")))
)
vis = {"min": 0, "max": 1, "palette": "ndvi"}
m.add_layer(ndvi_1999, vis, "NDVI")
m.add_colorbar(vis, label="NDVI")
m
# Load a Landsat 8 image.
image = ee.Image("LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318")
# Compute the EVI using an expression.
evi = image.expression(
"2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
{
"NIR": image.select("B5"),
"RED": image.select("B4"),
"BLUE": image.select("B2"),
},
)
# Define a map centered on San Francisco Bay.
m = geemap.Map(center=[37.4675, -122.1363], zoom=9)
vis = {"min": 0, "max": 1, "palette": "ndvi"}
m.add_layer(evi, vis, "EVI")
m.add_colorbar(vis, label="EVI")
m
Find out which state has the highest mean temperature in the United States on June 28, 2023. Relevant Earth Engine assets:
url = "https://github.com/giswqs/data/raw/main/raster/srtm90.tif"
filename = "dem.tif"
geemap.download_file(url, filename)
m = geemap.Map()
m.add_raster(filename, cmap="terrain", layer_name="DEM")
vis_params = {"min": 0, "max": 4000, "palette": "terrain"}
m.add_colorbar(vis_params, label="Elevation (m)")
m
url = "https://github.com/giswqs/data/raw/main/raster/cog.tif"
filename = "cog.tif"
geemap.download_file(url, filename)
m = geemap.Map()
m.add_raster(filename, indexes=[4, 1, 2], layer_name="False color")
m
in_geojson = (
"https://github.com/opengeos/datasets/releases/download/vector/cables.geojson"
)
m = geemap.Map()
m.add_geojson(in_geojson, layer_name="Cable lines", info_mode="on_hover")
m
m = geemap.Map()
m.add_basemap("CartoDB.DarkMatter")
callback = lambda feat: {"color": feat["properties"]["color"], "weight": 2}
m.add_geojson(in_geojson, layer_name="Cable lines", style_callback=callback)
m
url = "https://github.com/opengeos/datasets/releases/download/world/countries.geojson"
m = geemap.Map()
m.add_geojson(
url, layer_name="Countries", fill_colors=["red", "yellow", "green", "orange"]
)
m
import random
m = geemap.Map()
def random_color(feature):
return {
"color": "black",
"weight": 3,
"fillColor": random.choice(["red", "yellow", "green", "orange"]),
}
m.add_geojson(url, layer_name="Countries", style_callback=random_color)
m
m = geemap.Map()
style = {
"stroke": True,
"color": "#0000ff",
"weight": 2,
"opacity": 1,
"fill": True,
"fillColor": "#0000ff",
"fillOpacity": 0.1,
}
hover_style = {"fillOpacity": 0.7}
m.add_geojson(url, layer_name="Countries", style=style, hover_style=hover_style)
m
url = "https://github.com/opengeos/datasets/releases/download/world/countries.zip"
geemap.download_file(url, overwrite=True)
m = geemap.Map()
in_shp = "countries.shp"
m.add_shp(in_shp, layer_name="Countries")
m
import geopandas as gpd
m = geemap.Map(center=[40, -100], zoom=4)
gdf = gpd.read_file("countries.shp")
m.add_gdf(gdf, layer_name="Countries")
m
m = geemap.Map()
data = "https://github.com/opengeos/datasets/releases/download/world/countries.gpkg"
m.add_vector(data, layer_name="Countries")
m
data = "https://github.com/gee-community/geemap/blob/master/examples/data/us_cities.csv"
geemap.csv_to_df(data)
geemap.csv_to_geojson(
data, "cities.geojson", latitude="latitude", longitude="longitude"
)
geemap.csv_to_shp(data, "cities.shp", latitude="latitude", longitude="longitude")
geemap.csv_to_vector(data, "cities.gpkg", latitude="latitude", longitude="longitude")
gdf = geemap.csv_to_gdf(data, latitude="latitude", longitude="longitude")
gdf
cities = (
"https://github.com/gee-community/geemap/blob/master/examples/data/us_cities.csv"
)
m = geemap.Map(center=[40, -100], zoom=4)
m.add_points_from_xy(cities, x="longitude", y="latitude")
m
regions = "https://github.com/gee-community/geemap/blob/master/examples/data/us_regions.geojson"
m = geemap.Map(center=[40, -100], zoom=4)
m.add_geojson(regions, layer_name="US Regions")
m.add_points_from_xy(
cities,
x="longitude",
y="latitude",
layer_name="US Cities",
color_column="region",
icon_names=["gear", "map", "leaf", "globe"],
spin=True,
add_legend=True,
)
m
m = geemap.Map(center=[40, -100], zoom=4)
m.add_circle_markers_from_xy(
data,
x="longitude",
y="latitude",
radius=8,
color="blue",
fill_color="black",
fill_opacity=0.5,
)
m
m = geemap.Map()
url = "https://opendata.digitalglobe.com/events/california-fire-2020/pre-event/2018-02-16/pine-gulch-fire20/1030010076004E00.tif"
m.add_cog_layer(url, name="Fire (pre-event)")
m
geemap.cog_center(url)
geemap.cog_bands(url)
url2 = "https://opendata.digitalglobe.com/events/california-fire-2020/post-event/2020-08-14/pine-gulch-fire20/10300100AAC8DD00.tif"
m.add_cog_layer(url2, name="Fire (post-event)")
m = geemap.Map(center=[39.4568, -108.5107], zoom=12)
m.split_map(left_layer=url2, right_layer=url)
m
url = "https://tinyurl.com/22vptbws"
geemap.stac_bounds(url)
geemap.stac_center(url)
geemap.stac_bands(url)
m = geemap.Map()
m.add_stac_layer(url, bands=["pan"], name="Panchromatic")
m.add_stac_layer(url, bands=["B3", "B2", "B1"], name="False color")
m
m = geemap.Map()
image = ee.Image("LANDSAT/LC08/C02/T1_TOA/LC08_044034_20140318").select(
["B5", "B4", "B3"]
)
vis_params = {"min": 0, "max": 0.5, "gamma": [0.95, 1.1, 1]}
m.center_object(image)
m.add_layer(image, vis_params, "Landsat")
m
Add a rectangle to the map.
region = ee.Geometry.BBox(-122.5955, 37.5339, -122.0982, 37.8252)
fc = ee.FeatureCollection(region)
style = {"color": "ffff00ff", "fillColor": "00000000"}
m.add_layer(fc.style(**style), {}, "ROI")
To local drive
geemap.ee_export_image(image, filename="landsat.tif", scale=30, region=region)
Check image projection.
projection = image.select(0).projection().getInfo()
projection
crs = projection["crs"]
crs_transform = projection["transform"]
Specify region, crs, and crs_transform.
geemap.ee_export_image(
image,
filename="landsat_crs.tif",
crs=crs,
crs_transform=crs_transform,
region=region,
)
To Google Drive
geemap.ee_export_image_to_drive(
image, description="landsat", folder="export", region=region, scale=30
)
geemap.download_ee_image(image, "landsat.tif", scale=90)
point = ee.Geometry.Point(-99.2222, 46.7816)
collection = (
ee.ImageCollection("USDA/NAIP/DOQQ")
.filterBounds(point)
.filterDate("2008-01-01", "2018-01-01")
.filter(ee.Filter.listContains("system:band_names", "N"))
)
collection.aggregate_array("system:index")
To local drive
geemap.ee_export_image_collection(collection, out_dir=".", scale=10)
To Google Drive
geemap.ee_export_image_collection_to_drive(collection, folder="export", scale=10)
m = geemap.Map()
states = ee.FeatureCollection("TIGER/2018/States")
fc = states.filter(ee.Filter.eq("NAME", "Alaska"))
m.add_layer(fc, {}, "Alaska")
m.center_object(fc, 4)
m
To local drive
geemap.ee_to_shp(fc, filename="Alaska.shp")
geemap.ee_export_vector(fc, filename="Alaska.shp")
geemap.ee_to_geojson(fc, filename="Alaska.geojson")
geemap.ee_to_csv(fc, filename="Alaska.csv")
gdf = geemap.ee_to_gdf(fc)
gdf
df = geemap.ee_to_df(fc)
df
To Google Drive
geemap.ee_export_vector_to_drive(
fc, description="Alaska", fileFormat="SHP", folder="export"
)
m = geemap.Map(center=[41.718934, -86.894547], zoom=11)
m
Pan and zoom the map to an area of interest. Use the drawing tools to draw a rectangle on the map. If no rectangle is drawn, the default rectangle shown below will be used.
roi = m.user_roi
if roi is None:
roi = ee.Geometry.BBox(-87.1492, 41.5812, -86.7145, 41.7531)
m.add_layer(roi)
m.center_object(roi)
timelapse = geemap.landsat_timelapse(
roi,
out_gif="Fairbanks.gif",
start_year=2000,
end_year=2023,
start_date="06-01",
end_date="09-01",
bands=["SWIR1", "NIR", "Red"],
frames_per_second=5,
title="Landsat Timelapse",
progress_bar_color="blue",
mp4=True,
)
geemap.show_image(timelapse)
m = geemap.Map(center=[41.718934, -86.894547], zoom=11)
m.add_gui("timelapse")
m
m = geemap.Map()
roi = ee.Geometry.BBox(-115.5541, 35.8044, -113.9035, 36.5581)
m.add_layer(roi)
m.center_object(roi)
m
timelapse = geemap.landsat_timelapse(
roi,
out_gif="las_vegas.gif",
start_year=1984,
end_year=2023,
bands=["NIR", "Red", "Green"],
frames_per_second=5,
title="Las Vegas, NV",
font_color="blue",
)
geemap.show_image(timelapse)
m = geemap.Map()
roi = ee.Geometry.BBox(113.8252, 22.1988, 114.0851, 22.3497)
m.add_layer(roi)
m.center_object(roi)
m
timelapse = geemap.landsat_timelapse(
roi,
out_gif="hong_kong.gif",
start_year=1990,
end_year=2022,
start_date="01-01",
end_date="12-31",
bands=["SWIR1", "NIR", "Red"],
frames_per_second=3,
title="Hong Kong",
)
geemap.show_image(timelapse)
m = geemap.Map(center=[41.718934, -86.894547], zoom=12)
m
Pan and zoom the map to an area of interest. Use the drawing tools to draw a rectangle on the map. If no rectangle is drawn, the default rectangle shown below will be used.
roi = m.user_roi
if roi is None:
roi = ee.Geometry.BBox(-87.0492, 41.6545, -86.7903, 41.7604)
m.add_layer(roi)
m.center_object(roi)
timelapse = geemap.sentinel2_timelapse(
roi,
out_gif="sentinel2.gif",
start_year=2017,
end_year=2023,
start_date="06-01",
end_date="09-01",
frequency="year",
bands=["SWIR1", "NIR", "Red"],
frames_per_second=3,
title="Sentinel-2 Timelapse",
)
geemap.show_image(timelapse)
MODIS vegetation indices
m = geemap.Map()
m
roi = m.user_roi
if roi is None:
roi = ee.Geometry.BBox(-18.6983, -36.1630, 52.2293, 38.1446)
m.add_layer(roi)
m.center_object(roi)
timelapse = geemap.modis_ndvi_timelapse(
roi,
out_gif="ndvi.gif",
data="Terra",
band="NDVI",
start_date="2000-01-01",
end_date="2022-12-31",
frames_per_second=3,
title="MODIS NDVI Timelapse",
overlay_data="countries",
)
geemap.show_image(timelapse)
MODIS temperature
m = geemap.Map()
m
roi = m.user_roi
if roi is None:
roi = ee.Geometry.BBox(-171.21, -57.13, 177.53, 79.99)
m.add_layer(roi)
m.center_object(roi)
timelapse = geemap.modis_ocean_color_timelapse(
satellite="Aqua",
start_date="2018-01-01",
end_date="2020-12-31",
roi=roi,
frequency="month",
out_gif="temperature.gif",
overlay_data="continents",
overlay_color="yellow",
overlay_opacity=0.5,
)
geemap.show_image(timelapse)
roi = ee.Geometry.BBox(167.1898, -28.5757, 202.6258, -12.4411)
start_date = "2022-01-15T03:00:00"
end_date = "2022-01-15T07:00:00"
data = "GOES-17"
scan = "full_disk"
timelapse = geemap.goes_timelapse(
roi, "goes.gif", start_date, end_date, data, scan, framesPerSecond=5
)
geemap.show_image(timelapse)
roi = ee.Geometry.BBox(-159.5954, 24.5178, -114.2438, 60.4088)
start_date = "2021-10-24T14:00:00"
end_date = "2021-10-25T01:00:00"
data = "GOES-17"
scan = "full_disk"
timelapse = geemap.goes_timelapse(
roi, "hurricane.gif", start_date, end_date, data, scan, framesPerSecond=5
)
geemap.show_image(timelapse)
roi = ee.Geometry.BBox(-121.0034, 36.8488, -117.9052, 39.0490)
start_date = "2020-09-05T15:00:00"
end_date = "2020-09-06T02:00:00"
data = "GOES-17"
scan = "full_disk"
timelapse = geemap.goes_fire_timelapse(
roi, "fire.gif", start_date, end_date, data, scan, framesPerSecond=5
)
geemap.show_image(timelapse)
We will use the Hansen Global Forest Change v1.11 (2000-2023) dataset.
dataset = ee.Image("UMD/hansen/global_forest_change_2023_v1_11")
dataset.bandNames()
Select the imagery for 2000.
m = geemap.Map()
first_bands = ["first_b50", "first_b40", "first_b30"]
first_image = dataset.select(first_bands)
m.add_layer(first_image, {"bands": first_bands, "gamma": 1.5}, "Landsat 2000")
Select the imagery for 2023.
last_bands = ["last_b50", "last_b40", "last_b30"]
last_image = dataset.select(last_bands)
m.add_layer(last_image, {"bands": last_bands, "gamma": 1.5}, "Landsat 2023")
Select the tree cover imagery for 2000.
treecover = dataset.select(["treecover2000"])
treeCoverVisParam = {"min": 0, "max": 100, "palette": ["black", "green"]}
name = "Tree cover (%)"
m.add_layer(treecover, treeCoverVisParam, name)
m.add_colorbar(treeCoverVisParam, label=name, layer_name=name)
m.add("layer_manager")
m
Extract tree cover 2000 by using the threshold of 10%.
threshold = 10
treecover_bin = treecover.gte(threshold).selfMask()
treeVisParam = {"palette": ["green"]}
m.add_layer(treecover_bin, treeVisParam, "Tree cover bin")
Visualize forest loss.
m = geemap.Map(center=[64.864983, -147.840441], zoom=4)
m.add_basemap("Esri.WorldImagery")
treeloss_year = dataset.select(["lossyear"])
treeLossVisParam = {"min": 0, "max": 22, "palette": ["yellow", "red"]}
layer_name = "Tree loss year"
m.add_layer(treeloss_year, treeLossVisParam, layer_name)
m.add_colorbar(treeLossVisParam, label=layer_name, layer_name=layer_name)
m.add("layer_manager")
m
Compare forest loss and gain.
m = geemap.Map(center=[64.864983, -147.840441], zoom=4)
m.add_basemap("Esri.WorldImagery")
treeloss = dataset.select(["loss"]).selfMask()
treegain = dataset.select(["gain"]).selfMask()
m.add_layer(treeloss, {"palette": "red"}, "Tree loss")
m.add_layer(treegain, {"palette": "yellow"}, "Tree gain")
m.add("layer_manager")
m
Compute zonal statistics to find out which county in Alaska has the largest forest area in 2000.
Add a county boundary layer to the map.
counties = ee.FeatureCollection("TIGER/2018/Counties").filter(
ee.Filter.eq("STATEFP", "02")
)
df = geemap.ee_to_df(counties)
df.head()
style = {"color": "0000FFFF", "fillColor": "00000000"}
m.add_layer(counties, {}, "Counties Vector", False)
m.add_layer(counties.style(**style), {}, "Counties Raster")
m
Compute zonal statistics by county.
geemap.zonal_stats(
treecover_bin,
counties,
"forest_cover.csv",
stat_type="SUM",
denominator=1e6,
scale=300,
)
Create a pie chart to visualize the forest area by county.
geemap.pie_chart(
"forest_cover.csv", names="NAME", values="sum", max_rows=20, height=400
)
Create a bar chart to visualize the forest area by county.
geemap.bar_chart(
"forest_cover.csv",
x="NAME",
y="sum",
max_rows=20,
x_label="County",
y_label="Forest area (km2)",
)
Calculate the forest loss area by county.
geemap.zonal_stats(
treeloss.gt(0),
counties,
"treeloss.csv",
stat_type="SUM",
denominator=1e6,
scale=300,
)
Create a bar chart to visualize the forest loss area by county.
geemap.pie_chart("treeloss.csv", names="NAME", values="sum", max_rows=20, height=600)
Create a bar chart to visualize the forest loss area by county.
geemap.bar_chart(
"treeloss.csv",
x="NAME",
y="sum",
max_rows=20,
x_label="County",
y_label="Forest loss area (km2)",
)
Find out which US state has the largest forest gain and loss between 2000 and 2022. Create pie charts and bar charts to show the results. Relevant Earth Engine assets:
The 2020 North American Land Cover 30-meter dataset was produced as part of the North American Land Change Monitoring System (NALCMS), a trilateral effort between Natural Resources Canada, the United States Geological Survey, and three Mexican organizations.
m = geemap.Map(center=[40, -100], zoom=4, height=700)
m.add_basemap("Esri.WorldImagery", False)
landcover = ee.Image("USGS/NLCD_RELEASES/2020_REL/NALCMS")
states = ee.FeatureCollection("TIGER/2018/States")
fc = states.filter(ee.Filter.eq("NAME", "Alaska"))
legend_dict = {
"1 Temperate forest": "033e00",
"2 Sub-polar forest": "939b71",
"3 Tropical evergreen forest": "196d12",
"4 Tropical deciduous forest": "1fab01",
"5 Temperate deciduous forest": "5b725c",
"6 Mixed forest": "6b7d2c",
"7 Tropical shrubland": "b29d29",
"8 Temperate shrubland": "b48833",
"9 Tropical grassland": "e9da5d",
"10 Temperate grassland": "e0cd88",
"11 Sub-polar shrubland": "a07451",
"12 Sub-polar grassland": "bad292",
"13 Sub-polar barren": "3f8970",
"14 Wetland": "6ca289",
"15 Cropland": "e6ad6a",
"16 Barren land": "a9abae",
"17 Urban and built-up": "db2126",
"18 Water": "4c73a1",
"19 Snow and ice ": "fff7fe",
}
palette = list(legend_dict.values())
vis_params = {"palette": palette, "min": 1, "max": 19}
m.add_layer(landcover, vis_params, "NALCMS Land Cover")
m.add_layer(fc, {}, "Alaska", False)
m.center_object(fc, 4)
m.add_legend(title="Land Cover Type", legend_dict=legend_dict)
m
fig = geemap.image_histogram(
landcover, region=fc, x_label="Land cover type", y_label="Pixels"
)
fig
values = list(fig.data[0]["x"])
values
classes = [list(legend_dict.keys())[int(value) - 1] for value in values]
classes
fig.update_xaxes(tickvals=values, ticktext=classes)
fig
region = ee.Geometry.BBox(-149.352, 64.5532, -147.0976, 65.1277)
collection = geemap.landsat_timeseries(
region, start_year=2021, end_year=2021, start_date="06-01", end_date="09-01"
)
image = collection.first()
m = geemap.Map()
m.add_basemap("Esri.WorldImagery")
vis_params = {"min": 0, "max": 0.3, "bands": ["NIR", "Red", "Green"]}
m.add_layer(image, vis_params, "Image")
m.add_layer(landcover.clip(region), {}, "NALCMS land cover", False)
# m.add_legend(title='Land Cover Type', legend_dict=legend_dict, layer_name='NALCMS land cover')
m.center_object(region, 9)
m
training = image.sample(
**{
"region": region,
"scale": 150,
"numPixels": 5000,
"seed": 1,
"geometries": True,
}
)
m.add_layer(training, {}, "Training samples")
geemap.ee_to_df(training.limit(5))
clusterer = ee.Clusterer.wekaXMeans(minClusters=3, maxClusters=6).train(training)
result = image.cluster(clusterer)
m.add_layer(result.randomVisualizer(), {}, "Clusters")
m.add("layer_manager")
m
geemap.image_histogram(landcover, region=region, scale=30)
geemap.image_histogram(result, region=region, scale=300)
m = geemap.Map()
m.add_basemap("Esri.WorldImagery")
vis_params = {"min": 0, "max": 0.3, "bands": ["NIR", "Red", "Green"]}
m.add_layer(image, vis_params, "Image")
m.add_layer(landcover.clip(region), {}, "NALCMS land cover", False)
# m.add_legend(title='Land Cover Type', legend_dict=legend_dict, layer_name='NALCMS land cover')
m.center_object(region, 9)
m
points = landcover.sample(
**{
"region": region,
"scale": 150,
"numPixels": 5000,
"seed": 1,
"geometries": True,
}
)
m.add_layer(points, {}, "Training", False)
label = "landcover"
features = image.sampleRegions(
**{"collection": points, "properties": [label], "scale": 150}
)
geemap.ee_to_df(features.limit(5))
bands = image.bandNames().getInfo()
params = {
"features": features,
"classProperty": label,
"inputProperties": bands,
}
classifier = ee.Classifier.smileCart(maxNodes=None).train(**params)
classified = image.classify(classifier).rename("landcover")
m.add_layer(classified.randomVisualizer(), {}, "Classified")
m
class_values = list(range(1, 20))
class_palette = list(legend_dict.values())
classified = classified.set(
{"landcover_class_values": class_values, "landcover_class_palette": class_palette}
)
m.add_layer(classified, {}, "Land cover")
m.add_legend(title="Land cover type", builtin_legend="NLCD")
m
m = geemap.Map()
point = ee.Geometry.Point([-122.4439, 37.7538])
img = (
ee.ImageCollection("COPERNICUS/S2_SR")
.filterBounds(point)
.filterDate("2020-01-01", "2021-01-01")
.sort("CLOUDY_PIXEL_PERCENTAGE")
.first()
.select("B.*")
)
vis_params = {"min": 100, "max": 3500, "bands": ["B11", "B8", "B3"]}
m.centerObject(point, 9)
m.add_layer(img, vis_params, "Sentinel-2")
m
lc = ee.Image("ESA/WorldCover/v100/2020")
classValues = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100]
remapValues = ee.List.sequence(0, 10)
label = "lc"
lc = lc.remap(classValues, remapValues).rename(label).toByte()
sample = img.addBands(lc).stratifiedSample(
**{
"numPoints": 100,
"classBand": label,
"region": img.geometry(),
"scale": 10,
"geometries": True,
}
)
sample = sample.randomColumn()
trainingSample = sample.filter("random <= 0.8")
validationSample = sample.filter("random > 0.8")
trainedClassifier = ee.Classifier.smileRandomForest(numberOfTrees=10).train(
**{
"features": trainingSample,
"classProperty": label,
"inputProperties": img.bandNames(),
}
)
# print('Results of trained classifier', trainedClassifier.explain().getInfo())
trainAccuracy = trainedClassifier.confusionMatrix()
trainAccuracy.getInfo()
trainAccuracy.accuracy().getInfo()
trainAccuracy.kappa().getInfo()
validationSample = validationSample.classify(trainedClassifier)
validationAccuracy = validationSample.errorMatrix(label, "classification")
validationAccuracy.getInfo()
validationAccuracy.accuracy()
validationAccuracy.producersAccuracy().getInfo()
validationAccuracy.consumersAccuracy().getInfo()
import csv
with open("training.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(trainAccuracy.getInfo())
with open("validation.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(validationAccuracy.getInfo())
imgClassified = img.classify(trainedClassifier)
classVis = {
"min": 0,
"max": 10,
"palette": [
"006400",
"ffbb22",
"ffff4c",
"f096ff",
"fa0000",
"b4b4b4",
"f0f0f0",
"0064c8",
"0096a0",
"00cf75",
"fae6a0",
],
}
m.add_layer(lc, classVis, "ESA Land Cover", False)
m.add_layer(imgClassified, classVis, "Classified")
m.add_layer(trainingSample, {"color": "black"}, "Training sample")
m.add_layer(validationSample, {"color": "white"}, "Validation sample")
m.add_legend(title="Land Cover Type", builtin_legend="ESA_WorldCover")
m.centerObject(img)
m
Perform an unsupervised classification of a Sentinel-2 imagery for your preferred area. Relevant Earth Engine assets:
m = geemap.Map(center=(41.0462, -109.7424), zoom=6)
dem = ee.Image("USGS/SRTMGL1_003")
landsat7 = ee.Image("LANDSAT/LE7_TOA_5YEAR/1999_2003").select(
["B1", "B2", "B3", "B4", "B5", "B7"]
)
vis_params = {
"min": 0,
"max": 4000,
"palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
}
m.add_layer(
landsat7,
{"bands": ["B4", "B3", "B2"], "min": 20, "max": 200, "gamma": 2},
"landsat",
)
m.add_layer(dem, vis_params, "dem", True, 1)
m
try:
m.layer_to_image("dem", output="dem.tif", crs="EPSG:3857", region=None, scale=None)
m.layer_to_image("dem", output="dem.jpg", scale=500)
geemap.show_image("dem.jpg")
except:
pass
try:
m.layer_to_image("landsat", output="landsat.tif")
geemap.geotiff_to_image("landsat.tif", output="landsat.jpg")
geemap.show_image("landsat.jpg")
except:
pass
from geemap import cartoee
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from geemap import cartoee
srtm = ee.Image("CGIAR/SRTM90_V4")
# define bounding box [east, south, west, north] to request data
region = [180, -60, -180, 85]
vis = {"min": 0, "max": 3000}
fig = plt.figure(figsize=(15, 9))
# use cartoee to get a map
ax = cartoee.get_map(srtm, region=region, vis_params=vis)
# add a color bar to the map using the visualization params we passed to the map
cartoee.add_colorbar(
ax, vis, loc="bottom", label="Elevation (m)", orientation="horizontal"
)
# add grid lines to the map at a specified interval
cartoee.add_gridlines(ax, interval=[60, 30], linestyle=":")
# add coastlines using the cartopy api
ax.coastlines(color="red")
plt.show()
fig = plt.figure(figsize=(15, 7))
cmap = "terrain"
ax = cartoee.get_map(srtm, region=region, vis_params=vis, cmap=cmap)
cartoee.add_colorbar(
ax, vis, cmap=cmap, loc="right", label="Elevation (m)", orientation="vertical"
)
cartoee.add_gridlines(ax, interval=[60, 30], linestyle="--")
ax.coastlines(color="red")
ax.set_title(label="Global Elevation Map", fontsize=15)
plt.show()
cartoee.savefig(fig, fname="srtm.jpg", dpi=300, bbox_inches="tight")
image = ee.Image("LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318")
vis = {"bands": ["B5", "B4", "B3"], "min": 0, "max": 5000, "gamma": 1.3}
fig = plt.figure(figsize=(15, 10))
ax = cartoee.get_map(image, vis_params=vis)
cartoee.pad_view(ax)
cartoee.add_gridlines(ax, interval=0.5, xtick_rotation=0, linestyle=":")
ax.coastlines(color="yellow")
plt.show()
fig = plt.figure(figsize=(15, 10))
region = [-121.8025, 37.3458, -122.6265, 37.9178]
ax = cartoee.get_map(image, vis_params=vis, region=region)
cartoee.add_gridlines(ax, interval=0.15, xtick_rotation=0, linestyle=":")
ax.coastlines(color="yellow")
plt.show()
ocean = (
ee.ImageCollection("NASA/OCEANDATA/MODIS-Terra/L3SMI")
.filter(ee.Filter.date("2018-01-01", "2018-03-01"))
.median()
.select(["sst"], ["SST"])
)
visualization = {"bands": "SST", "min": -2, "max": 30}
bbox = [180, -88, -180, 88]
fig = plt.figure(figsize=(15, 10))
ax = cartoee.get_map(ocean, cmap="plasma", vis_params=visualization, region=bbox)
cb = cartoee.add_colorbar(ax, vis_params=visualization, loc="right", cmap="plasma")
ax.set_title(label="Sea Surface Temperature", fontsize=15)
ax.coastlines()
plt.show()
cartoee.savefig(fig, "SST.jpg", dpi=300)
import cartopy.crs as ccrs
fig = plt.figure(figsize=(15, 10))
projection = ccrs.Mollweide(central_longitude=-180)
ax = cartoee.get_map(
ocean, vis_params=visualization, region=bbox, cmap="plasma", proj=projection
)
cb = cartoee.add_colorbar(
ax, vis_params=visualization, loc="bottom", cmap="plasma", orientation="horizontal"
)
ax.set_title("Mollweide projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15, 10))
projection = ccrs.Robinson(central_longitude=-180)
ax = cartoee.get_map(
ocean, vis_params=visualization, region=bbox, cmap="plasma", proj=projection
)
cb = cartoee.add_colorbar(
ax, vis_params=visualization, loc="bottom", cmap="plasma", orientation="horizontal"
)
ax.set_title("Robinson projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15, 10))
projection = ccrs.InterruptedGoodeHomolosine(central_longitude=-180)
ax = cartoee.get_map(
ocean, vis_params=visualization, region=bbox, cmap="plasma", proj=projection
)
cb = cartoee.add_colorbar(
ax, vis_params=visualization, loc="bottom", cmap="plasma", orientation="horizontal"
)
ax.set_title("Goode homolosine projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(15, 10))
projection = ccrs.EqualEarth(central_longitude=-180)
ax = cartoee.get_map(
ocean, vis_params=visualization, region=bbox, cmap="plasma", proj=projection
)
cb = cartoee.add_colorbar(
ax, vis_params=visualization, loc="right", cmap="plasma", orientation="vertical"
)
ax.set_title("Equal Earth projection")
ax.coastlines()
plt.show()
fig = plt.figure(figsize=(11, 10))
projection = ccrs.Orthographic(-130, -10)
ax = cartoee.get_map(
ocean, vis_params=visualization, region=bbox, cmap="plasma", proj=projection
)
cb = cartoee.add_colorbar(
ax, vis_params=visualization, loc="right", cmap="plasma", orientation="vertical"
)
ax.set_title("Orographic projection")
ax.coastlines()
plt.show()
Create and export a global NDVI map using MODIS data. Relevant Earth Engine assets:
import ee
import geemap
import solara
class Map(geemap.Map):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_ee_data()
def add_ee_data(self):
years = ["2001", "2004", "2006", "2008", "2011", "2013", "2016", "2019"]
def getNLCD(year):
dataset = ee.ImageCollection("USGS/NLCD_RELEASES/2019_REL/NLCD")
nlcd = dataset.filter(ee.Filter.eq("system:index", year)).first()
landcover = nlcd.select("landcover")
return landcover
collection = ee.ImageCollection(ee.List(years).map(lambda year: getNLCD(year)))
labels = [f"NLCD {year}" for year in years]
self.ts_inspector(
left_ts=collection,
right_ts=collection,
left_names=labels,
right_names=labels,
)
self.add_legend(
title="NLCD Land Cover Type",
builtin_legend="NLCD",
height="460px",
add_header=False,
)
@solara.component
def Page():
with solara.Column(style={"min-width": "500px"}):
Map.element(
center=[40, -100],
zoom=4,
height="800px",
)
Page()
solara run ./pages
# geemap.get_ee_token()