import ee
import streamlit as st
import geemap.foliumap as geemap
import json
st.set_page_config(layout="wide")
st.sidebar.info(
"""
- Web App URL: <https://streamlit.geemap.org>
- GitHub repository: <https://github.com/giswqs/streamlit-geospatial>
"""
)
st.sidebar.title("Contact")
st.sidebar.info(
"""
Qiusheng Wu: <https://wetlands.io>
[GitHub](https://github.com/giswqs) | [Twitter](https://twitter.com/giswqs) | [YouTube](https://www.youtube.com/c/QiushengWu) | [LinkedIn](https://www.linkedin.com/in/qiushengwu)
"""
)
def nlcd():
# st.header("National Land Cover Database (NLCD)")
row1_col1, row1_col2 = st.columns([3, 1])
width = 950
height = 600
Map = geemap.Map(center=[40, -100], zoom=4)
# Select the seven NLCD epoches after 2000.
years = ["2001", "2004", "2006", "2008", "2011", "2013", "2016", "2019"]
# Get an NLCD image by year.
def getNLCD(year):
# Import the NLCD collection.
dataset = ee.ImageCollection("USGS/NLCD_RELEASES/2019_REL/NLCD")
# Filter the collection by year.
nlcd = dataset.filter(ee.Filter.eq("system:index", year)).first()
# Select the land cover band.
landcover = nlcd.select("landcover")
return landcover
with row1_col2:
selected_year = st.multiselect("Select a year", years)
add_legend = st.checkbox("Show legend")
if selected_year:
for year in selected_year:
Map.addLayer(getNLCD(year), {}, "NLCD " + year)
if add_legend:
Map.add_legend(
legend_title="NLCD Land Cover Classification", builtin_legend="NLCD"
)
with row1_col1:
Map.to_streamlit(width=width, height=height)
else:
with row1_col1:
Map.to_streamlit(width=width, height=height)
def search_data():
# st.header("Search Earth Engine Data Catalog")
Map = geemap.Map()
if "ee_assets" not in st.session_state:
st.session_state["ee_assets"] = None
if "asset_titles" not in st.session_state:
st.session_state["asset_titles"] = None
col1, col2 = st.columns([2, 1])
dataset = None
with col2:
keyword = st.text_input("Enter a keyword to search (e.g., elevation)", "")
if keyword:
ee_assets = geemap.search_ee_data(keyword)
asset_titles = [x["title"] for x in ee_assets]
asset_types = [x["type"] for x in ee_assets]
translate = {
"image_collection": "ee.ImageCollection('",
"image": "ee.Image('",
"table": "ee.FeatureCollection('",
"table_collection": "ee.FeatureCollection('",
}
dataset = st.selectbox("Select a dataset", asset_titles)
if len(ee_assets) > 0:
st.session_state["ee_assets"] = ee_assets
st.session_state["asset_titles"] = asset_titles
if dataset is not None:
with st.expander("Show dataset details", True):
index = asset_titles.index(dataset)
html = geemap.ee_data_html(st.session_state["ee_assets"][index])
html = html.replace("\n", "")
st.markdown(html, True)
ee_id = ee_assets[index]["id"]
uid = ee_assets[index]["uid"]
st.markdown(f"""**Earth Engine Snippet:** `{ee_id}`""")
ee_asset = f"{translate[asset_types[index]]}{ee_id}')"
vis_params = st.text_input(
"Enter visualization parameters as a dictionary", {}
)
layer_name = st.text_input("Enter a layer name", uid)
button = st.button("Add dataset to map")
if button:
vis = {}
try:
if vis_params.strip() == "":
# st.error("Please enter visualization parameters")
vis_params = "{}"
vis = eval(vis_params)
if not isinstance(vis, dict):
st.error("Visualization parameters must be a dictionary")
try:
Map.addLayer(eval(ee_asset), vis, layer_name)
except Exception as e:
st.error(f"Error adding layer: {e}")
except Exception as e:
st.error(f"Invalid visualization parameters: {e}")
with col1:
Map.to_streamlit()
else:
with col1:
Map.to_streamlit()
def app():
st.title("Earth Engine Data Catalog")
# Data from the downloaded JSON file
json_data = '''
{
"type": "service_account",
"project_id": "contactniravv",
"private_key_id": "2311ce3809826bb550cb098e057ee2e6068a40ff",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCfVeKcdOhL7NCQ\nA9mQiKjF5Ob0HcDk1fUIV+hUAqnQr2EK97kJ7q2sEs4FqhY38k0CBSo4NZybGJks\nI6caNfol7ob/fMnSZkOc0vXb4IWlK5wxsW0bA8eBd1OItB9ydhsP8OsZLexJdOX5\nUimwKgpm3nn0irEVA5Jx88omrtVTilOjeBj+IVSI49JLoI+69fXL01hCa5j3/DJH\nG5LyJ3/VwY9M9ajmQjxGyKCZrT2sQDa5f8XJ9jE/mmtHn68u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R0gTlCOpH48DBlNdHSzNYy/M0S/jjojKCks6D09w9+DB/zYGmlHfJK7bGn1S3Y4\nbF/KVNrKxZ3yAkZs04GOYToorQLV9lzZSzP7U8JV0QKBgEUzZAy52HtD1fGaqFw7\nHA6DKkxIgSwsUKZT+l+C3gK/I7py1zEpp6BZnLunNLIqIdvr8v4Mg4wZwbKcEL3c\nkbSyy8UDIFMUCe19y1zPdxBe9PngJYIkKVxAr5xR1/zB0n6cPX0ZX1Jc9900DLlJ\nNrXJpx1EflUlNzxEOve2kKr2\n-----END PRIVATE KEY-----\n",
"client_email": "contactniravv@contactniravv.iam.gserviceaccount.com",
"client_id": "107657170325250962617",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/contactniravv%40contactniravv.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}
'''
# Preparing values
json_object = json.loads(json_data, strict=False)
service_account = json_object['client_email']
json_object = json.dumps(json_object)
# Authorising the app
credentials = ee.ServiceAccountCredentials(service_account, key_data=json_object)
ee.Initialize(credentials)
apps = ["Search Earth Engine Data Catalog", "National Land Cover Database (NLCD)"]
selected_app = st.selectbox("Select an app", apps)
if selected_app == "National Land Cover Database (NLCD)":
nlcd()
elif selected_app == "Search Earth Engine Data Catalog":
search_data()
app()