92 plotly
Uncomment the following line to install geemap if needed.
# !pip install geema
import ee
import geemap.plotlymap as geemap
If you are using a recently implemented geema feature that has not yet been released to PyPI or conda-forge, you can uncomment the following line to install the development version from GitHub.
# geemap.update_package()
If you run into an error saying "FigureWidget - 'mapbox._derived' Value Error" (source), uncomment the following line and run it.
# geemap.fix_widget_error()
Create an interactive map using default settings.
m = geemap.Map()
m
Change default setting when creating a map.
Can be one of string from "open-street-map", "carto-positron", "carto-darkmatter", "stamen-terrain", "stamen-toner" or "stamen-watercolor" .
m = geemap.Map(center=(40, -100), zoom=3, basemap="stamen-terrain", height=500)
m
Set map center and zoom level.
m = geemap.Map(basemap="stamen-watercolor")
m.set_center(lat=20, lon=0, zoom=2)
m
Print out available basemaps.
geemap.plotly_basemaps.keys()
dict_keys(['OpenStreetMap', 'ROADMAP', 'SATELLITE', 'TERRAIN', 'HYBRID', 'BasemapAT.basemap', 'BasemapAT.grau', 'BasemapAT.highdpi', 'BasemapAT.orthofoto', 'BasemapAT.overlay', 'BasemapAT.surface', 'BasemapAT.terrain', 'CartoDB.DarkMatter', 'CartoDB.DarkMatterNoLabels', 'CartoDB.DarkMatterOnlyLabels', 'CartoDB.Positron', 'CartoDB.PositronNoLabels', 'CartoDB.PositronOnlyLabels', 'CartoDB.Voyager', 'CartoDB.VoyagerLabelsUnder', 'CartoDB.VoyagerNoLabels', 'CartoDB.VoyagerOnlyLabels', 'CyclOSM', 'Esri.AntarcticBasemap', 'Esri.ArcticOceanBase', 'Esri.ArcticOceanReference', 'Esri.DeLorme', 'Esri.NatGeoWorldMap', 'Esri.OceanBasemap', 'Esri.WorldGrayCanvas', 'Esri.WorldImagery', 'Esri.WorldPhysical', 'Esri.WorldShadedRelief', 'Esri.WorldStreetMap', 'Esri.WorldTerrain', 'Esri.WorldTopoMap', 'FreeMapSK', 'Gaode.Normal', 'Gaode.Satellite', 'GeoportailFrance.orthos', 'GeoportailFrance.parcels', 'GeoportailFrance.plan', 'HikeBike.HikeBike', 'HikeBike.HillShading', 'Hydda.Base', 'Hydda.Full', 'Hydda.RoadsAndLabels', 'JusticeMap.americanIndian', 'JusticeMap.asian', 'JusticeMap.black', 'JusticeMap.hispanic', 'JusticeMap.income', 'JusticeMap.multi', 'JusticeMap.nonWhite', 'JusticeMap.plurality', 'JusticeMap.white', 'MtbMap', 'NASAGIBS.BlueMarble', 'NASAGIBS.BlueMarble3031', 'NASAGIBS.BlueMarble3413', 'NASAGIBS.ModisAquaBands721CR', 'NASAGIBS.ModisAquaTrueColorCR', 'NASAGIBS.ModisTerraAOD', 'NASAGIBS.ModisTerraBands367CR', 'NASAGIBS.ModisTerraBands721CR', 'NASAGIBS.ModisTerraChlorophyll', 'NASAGIBS.ModisTerraLSTDay', 'NASAGIBS.ModisTerraSnowCover', 'NASAGIBS.ModisTerraTrueColorCR', 'NASAGIBS.ViirsEarthAtNight2012', 'NASAGIBS.ViirsTrueColorCR', 'NLS', 'OPNVKarte', 'OneMapSG.Default', 'OneMapSG.Grey', 'OneMapSG.LandLot', 'OneMapSG.Night', 'OneMapSG.Original', 'OpenAIP', 'OpenFireMap', 'OpenRailwayMap', 'OpenSeaMap', 'OpenSnowMap.pistes', 'OpenStreetMap.BZH', 'OpenStreetMap.BlackAndWhite', 'OpenStreetMap.CH', 'OpenStreetMap.DE', 'OpenStreetMap.France', 'OpenStreetMap.HOT', 'OpenStreetMap.Mapnik', 'OpenTopoMap', 'SafeCast', 'Stadia.AlidadeSmooth', 'Stadia.AlidadeSmoothDark', 'Stadia.OSMBright', 'Stadia.Outdoors', 'Stamen.Terrain', 'Stamen.TerrainBackground', 'Stamen.TerrainLabels', 'Stamen.Toner', 'Stamen.TonerBackground', 'Stamen.TonerHybrid', 'Stamen.TonerLabels', 'Stamen.TonerLines', 'Stamen.TonerLite', 'Stamen.TopOSMFeatures', 'Stamen.TopOSMRelief', 'Stamen.Watercolor', 'Strava.All', 'Strava.Ride', 'Strava.Run', 'Strava.Water', 'Strava.Winter', 'SwissFederalGeoportal.JourneyThroughTime', 'SwissFederalGeoportal.NationalMapColor', 'SwissFederalGeoportal.NationalMapGrey', 'SwissFederalGeoportal.SWISSIMAGE', 'USGS.USImagery', 'USGS.USImageryTopo', 'USGS.USTopo', 'WaymarkedTrails.cycling', 'WaymarkedTrails.hiking', 'WaymarkedTrails.mtb', 'WaymarkedTrails.riding', 'WaymarkedTrails.skating', 'WaymarkedTrails.slopes', 'nlmaps.grijs', 'nlmaps.luchtfoto', 'nlmaps.pastel', 'nlmaps.standaard', 'nlmaps.water'])
Add a basemap.
m = geemap.Map()
m.add_basemap("OpenTopoMap")
m
Add XYZ tile layer.
m = geemap.Map()
tile_url = "https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}"
m.add_tile_layer(tile_url, name="Google Satellite", attribution="Google", opacity=1.0)
m
Add a mapbox tile layer. You will need a mapbox token. The map style can be Can be "basic", "streets", "outdoors", "light", "dark", "satellite", or "satellite-streets".
import os
# os.environ["MAPBOX_TOKEN"] = "your-mapbox-token"
m = geemap.Map()
m.add_mapbox_layer(style="streets")
m
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [13], in <cell line: 2>() 1 m = geemap.Map() ----> 2 m.add_mapbox_layer(style="streets") 3 m File ~/.local/lib/python3.9/site-packages/geemap/plotlymap.py:224, in Map.add_mapbox_layer(self, style, access_token) 221 if access_token is None: 222 access_token = os.environ.get("MAPBOX_TOKEN") --> 224 self.update_layout( 225 mapbox_style=style, mapbox_layers=[], mapbox_accesstoken=access_token 226 ) File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:1403, in BaseFigure.update_layout(self, dict1, overwrite, **kwargs) 1379 def update_layout(self, dict1=None, overwrite=False, **kwargs): 1380 """ 1381 Update the properties of the figure's layout with a dict and/or with 1382 keyword arguments. (...) 1401 The Figure object that the update_layout method was called on 1402 """ -> 1403 self.layout.update(dict1, overwrite=overwrite, **kwargs) 1404 return self File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:5090, in BasePlotlyType.update(self, dict1, overwrite, **kwargs) 5088 with self.figure.batch_update(): 5089 BaseFigure._perform_update(self, dict1, overwrite=overwrite) -> 5090 BaseFigure._perform_update(self, kwargs, overwrite=overwrite) 5091 else: 5092 BaseFigure._perform_update(self, dict1, overwrite=overwrite) File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:3929, in BaseFigure._perform_update(plotly_obj, update_obj, overwrite) 3926 plotly_obj[key] = val 3927 else: 3928 # Assign non-compound value -> 3929 plotly_obj[key] = val 3931 elif isinstance(plotly_obj, tuple): 3933 if len(update_obj) == 0: 3934 # Nothing to do File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:5818, in BaseLayoutType.__setitem__(self, prop, value) 5815 prop_tuple = BaseFigure._str_to_dict_path(prop) 5816 if len(prop_tuple) != 1 or not isinstance(prop_tuple[0], string_types): 5817 # Let parent handle non-scalar non-string cases -> 5818 super(BaseLayoutHierarchyType, self).__setitem__(prop, value) 5819 return 5820 else: 5821 # Unwrap prop tuple File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:4867, in BasePlotlyType.__setitem__(self, prop, value) 4863 res = res[p] 4865 res._validate = self._validate -> 4867 res[prop[-1]] = value File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:4827, in BasePlotlyType.__setitem__(self, prop, value) 4823 self._set_array_prop(prop, value) 4825 # ### Handle simple property ### 4826 else: -> 4827 self._set_prop(prop, value) 4828 else: 4829 # Make sure properties dict is initialized 4830 self._init_props() File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:5171, in BasePlotlyType._set_prop(self, prop, val) 5169 return 5170 else: -> 5171 raise err 5173 # val is None 5174 # ----------- 5175 if val is None: 5176 # Check if we should send null update File ~/.local/lib/python3.9/site-packages/plotly/basedatatypes.py:5166, in BasePlotlyType._set_prop(self, prop, val) 5163 validator = self._get_validator(prop) 5165 try: -> 5166 val = validator.validate_coerce(val) 5167 except ValueError as err: 5168 if self._skip_invalid: File ~/.local/lib/python3.9/site-packages/_plotly_utils/basevalidators.py:1106, in StringValidator.validate_coerce(self, v) 1103 self.raise_invalid_val(v) 1105 if self.no_blank and len(v) == 0: -> 1106 self.raise_invalid_val(v) 1108 if self.values and v not in self.values: 1109 self.raise_invalid_val(v) File ~/.local/lib/python3.9/site-packages/_plotly_utils/basevalidators.py:289, in BaseValidator.raise_invalid_val(self, v, inds) 286 for i in inds: 287 name += "[" + str(i) + "]" --> 289 raise ValueError( 290 """ 291 Invalid value of type {typ} received for the '{name}' property of {pname} 292 Received value: {v} 293 294 {valid_clr_desc}""".format( 295 name=name, 296 pname=self.parent_name, 297 typ=type_str(v), 298 v=repr(v), 299 valid_clr_desc=self.description(), 300 ) 301 ) ValueError: Invalid value of type 'builtins.str' received for the 'accesstoken' property of layout.mapbox Received value: '' The 'accesstoken' property is a string and must be specified as: - A non-empty string
Remove the modebar in the upper-right corner.
m = geemap.Map(basemap="stamen-toner")
m
m.clear_controls()
Add more buttons to the modebar.
m = geemap.Map(basemap="carto-positron")
controls = [
'drawline',
'drawopenpath',
'drawclosedpath',
'drawcircle',
'drawrect',
'eraseshape',
]
m.add_controls(controls)
m
Add Cloud Optimized GeoTIFF.
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
Add a STAC item via HTTP URL.
m = geemap.Map()
url = 'https://canada-spot-ortho.s3.amazonaws.com/canada_spot_orthoimages/canada_spot5_orthoimages/S5_2007/S5_11055_6057_20070622/S5_11055_6057_20070622.json'
m.add_stac_layer(url, bands=['B3', 'B2', 'B1'], name='False color')
m
Add a STAC item from Microsoft Planetary Computer.
collection = "landsat-8-c2-l2"
items = "LC08_L2SP_047027_20201204_02_T1"
m = geemap.Map()
m.add_stac_layer(
collection=collection,
items=items,
bands=["SR_B7", "SR_B5", "SR_B4"],
titiler_endpoint="pc",
)
m
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Input In [20], in <cell line: 2>() 1 m = geemap.Map() ----> 2 m.add_stac_layer( 3 collection=collection, 4 items=items, 5 bands=["SR_B7", "SR_B5", "SR_B4"], 6 titiler_endpoint="pc", 7 ) 8 m File ~/.local/lib/python3.9/site-packages/geemap/plotlymap.py:527, in Map.add_stac_layer(self, url, collection, item, assets, bands, titiler_endpoint, name, attribution, opacity, **kwargs) 501 def add_stac_layer( 502 self, 503 url=None, (...) 512 **kwargs, 513 ): 514 """Adds a STAC TileLayer to the map. 515 516 Args: (...) 525 opacity (float, optional): The opacity of the layer. Defaults to 1. 526 """ --> 527 tile_url = stac_tile( 528 url, collection, item, assets, bands, titiler_endpoint, **kwargs 529 ) 530 center = stac_center(url, collection, item, titiler_endpoint) 531 self.add_tile_layer(tile_url, name, attribution, opacity) File ~/.local/lib/python3.9/site-packages/geemap/common.py:4553, in stac_tile(url, collection, item, assets, bands, titiler_endpoint, **kwargs) 4540 if ( 4541 (assets is not None) 4542 and ("asset_expression" not in kwargs) 4543 and ("expression" not in kwargs) 4544 and ("rescale" not in kwargs) 4545 ): 4546 stats = stac_stats( 4547 collection=collection, 4548 item=item, 4549 assets=assets, 4550 titiler_endpoint=titiler_endpoint, 4551 ) 4552 percentile_2 = min( -> 4553 [stats[s][list(stats[s].keys())[0]]["percentile_2"] for s in stats] 4554 ) 4555 percentile_98 = max( 4556 [stats[s][list(stats[s].keys())[0]]["percentile_98"] for s in stats] 4557 ) 4558 kwargs["rescale"] = f"{percentile_2},{percentile_98}" File ~/.local/lib/python3.9/site-packages/geemap/common.py:4553, in <listcomp>(.0) 4540 if ( 4541 (assets is not None) 4542 and ("asset_expression" not in kwargs) 4543 and ("expression" not in kwargs) 4544 and ("rescale" not in kwargs) 4545 ): 4546 stats = stac_stats( 4547 collection=collection, 4548 item=item, 4549 assets=assets, 4550 titiler_endpoint=titiler_endpoint, 4551 ) 4552 percentile_2 = min( -> 4553 [stats[s][list(stats[s].keys())[0]]["percentile_2"] for s in stats] 4554 ) 4555 percentile_98 = max( 4556 [stats[s][list(stats[s].keys())[0]]["percentile_98"] for s in stats] 4557 ) 4558 kwargs["rescale"] = f"{percentile_2},{percentile_98}" AttributeError: 'list' object has no attribute 'keys'
Add a heat map.
url = 'https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv'
m = geemap.Map(basemap="stamen-terrain")
m.add_heatmap(
url, latitude="Latitude", longitude="Longitude", z="Magnitude", name="Earthquake"
)
m
Add a choropleth map.
url = "https://raw.githubusercontent.com/giswqs/geemap/master/examples/data/countries.geojson"
m = geemap.Map(basemap="stamen-terrain")
m.add_choropleth_map(url, name="Pop", z="POP_EST", colorscale="Viridis")
m
Add Earth Engine layers.
m = geemap.Map()
m.add_basemap("HYBRID")
# Add Earth Engine dataset
dem = ee.Image('USGS/SRTMGL1_003')
landsat7 = ee.Image('LE7_TOA_5YEAR/1999_2003').select(
['B1', 'B2', 'B3', 'B4', 'B5', 'B7']
)
states = ee.FeatureCollection("TIGER/2018/States")
# Set visualization parameters.
vis_params = {
'min': 0,
'max': 4000,
'palette': ['006633', 'E5FFCC', '662A00', 'D8D8D8', 'F5F5F5'],
}
# Add Earth Eninge layers to Map
m.addLayer(dem, vis_params, 'SRTM DEM', True, 0.5)
m.addLayer(
landsat7,
{'bands': ['B4', 'B3', 'B2'], 'min': 20, 'max': 200, 'gamma': 2.0},
'Landsat 7',
)
m.addLayer(states, {}, "US States")
m.show()