Enable GEE API and create web UI

2 min read
Log into Google Cloud Console
Select the project and “IAM & Admin” tab
Create service account
Create new key (JSON) and save in your local computer
Check the account is added
Install necessary packages
pip install earthengine-api streamlit folium streamlit-folium
import ee import streamlit as st import datetime import os # Initialize GEE authentication and setup service_account = 'orbtrace@forest-in-rochester-hills.iam.gserviceaccount.com' script_dir = os.path.dirname(os.path.abspath(__file__)) key_path = os.path.join(script_dir, '../../GoogleCloudKeys/forest-in-rochester-hills-084f70827372.json') credentials = ee.ServiceAccountCredentials(service_account, key_path) ee.Initialize(credentials) st.title("Yearly Satellite Image NDVI Viewer") # Year selection UI slider year = st.slider("Select the year", 2015, datetime.datetime.now().year, 2020) # Set date range based on selected year start_date = f'{year}-01-01' end_date = f'{year}-12-31' # Retrieve Sentinel-2 image collection from GEE filtered by date, location, and cloud cover collection = (ee.ImageCollection('COPERNICUS/S2_SR') .filterDate(start_date, end_date) .filterBounds(ee.Geometry.Point(-83.141, 42.658)) # Example coordinate for Rochester Hills .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))) # Compute median image from collection image = collection.median() # Calculate NDVI using NIR (B8) and Red (B4) bands ndvi = image.normalizedDifference(['B8', 'B4']).rename('NDVI') # Visualization parameters for NDVI image ndvi_params = { 'min': 0.0, 'max': 1.0, 'palette': ['white', 'green'] } # Convert NDVI image to a tile map URL map_id_dict = ndvi.getMapId(ndvi_params) tile_url = map_id_dict['tile_fetcher'].url_format st.write(f"Selected year: {year}") # Import folium and streamlit_folium for displaying tile map on Streamlit (optional) import folium from streamlit_folium import st_folium # Create map centered at Rochester Hills coordinates m = folium.Map(location=[42.658, -83.141], zoom_start=11) folium.TileLayer( tiles=tile_url, attr='Google Earth Engine', name='NDVI', overlay=True, control=True ).add_to(m) # Display the map on Streamlit app st_folium(m, width=700, height=500)
Go to the file directory and run the code
streamlit run app.py
0
Subscribe to my newsletter
Read articles from Jinyoung Park directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
