### Python Installation Guide
Source: https://github.com/google/earthengine-api/blob/master/python/README.md
Instructions for installing and setting up the Google Earth Engine Python API. This guide covers necessary steps to get started with using Earth Engine in Python.
```python
# Visit the Google Earth Engine Python installation page for set up instructions.
# https://developers.google.com/earth-engine/python_install
```
--------------------------------
### Navigate to Server Auth Example
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-python/README.md
Changes the current directory to the server-side authentication example within the cloned Earth Engine API repository. This is where the demo code resides.
```bash
cd ./earthengine-api/demos/server-auth-python
```
--------------------------------
### Run Local Demo
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Starts a local development server to preview the client webpage.
```Bash
npm run dev
```
--------------------------------
### Install Dependencies
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Installs the necessary Node.js packages for the project.
```Bash
npm install
```
--------------------------------
### Google Earth Engine JavaScript Installation
Source: https://github.com/google/earthengine-api/blob/master/javascript/README.md
Instructions for setting up the Google Earth Engine API for JavaScript development. This includes options for NPM installation or direct script inclusion.
```javascript
// Option 1: NPM Installation
// npm install @google/earthengine
// Option 2: Direct script inclusion
// Include the ee_api_js.js file in your HTML
//
// For setup instructions, visit: https://developers.google.com/earth-engine/npm_install
```
--------------------------------
### Install Dependencies
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Installs the necessary Python libraries, geemap and earthengine-api, for the demonstration.
```python
# @title Prerequisites
# Install 'geemap' library to display the map.
!pip install geemap
!pip install earthengine-api --upgrade
```
--------------------------------
### Navigate to Interactive Classifier Demo
Source: https://github.com/google/earthengine-api/blob/master/demos/interactive-classifier/README.md
Command to change the directory to the interactive classifier example within the cloned repository.
```bash
cd ./earthengine-api/demos/interactive-classifier
```
--------------------------------
### Earth Engine Server Auth Setup Steps
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-python/README.md
Outlines the steps required to set up server-side authentication for a Google Earth Engine application using Python and Google App Engine. This includes obtaining a Service Account, placing its private key, creating a Google Maps API key, and copying necessary JavaScript files.
```bash
# 1. Move the Service Account private key (.private-key.json) into the demos/server-auth-python folder.
# 2. [Create an API key](https://developers.google.com/maps/documentation/javascript/get-api-key) and include it in index.html to load Google Maps API.
# 3. Copy javascript/build/ee_api_js.js into demos/server-auth-python/static/.
```
--------------------------------
### Navigate to Node.js Server Auth Demo
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-nodejs/README.md
Changes the current directory to the Node.js server authentication example within the Earth Engine API repository.
```bash
cd ./earthengine-api/demos/server-auth-nodejs
```
--------------------------------
### Client.js Configuration
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Example configuration for client.js, showing how to set the Cloud Function endpoint URL.
```JavaScript
// Replace CLOUD_FN_ENDPOINT with your Cloud Function URL
const CLOUD_FN_ENDPOINT = "YOUR_CLOUD_FUNCTION_URL";
```
--------------------------------
### Initialize Maps API and Add Earth Engine Layer
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-nodejs/index.html
Initializes the Google Maps JavaScript API, creates a map instance, and adds an Earth Engine tile source to it. It fetches a mapid from a server endpoint to configure the tile source.
```javascript
const initialize = (mapid) => {
const mapContainerEl = document.getElementById("map-container");
const embeddedMap = new google.maps.Map(mapContainerEl, {
center: { lng: -112.8598, lat: 36.2841 },
zoom: 9,
});
const tileSource = new ee.layers.EarthEngineTileSource({
mapid,
});
const overlay = new ee.layers.ImageOverlay(tileSource);
embeddedMap.overlayMapTypes.push(overlay);
};
fetch("/mapid")
.then((response) => response.text())
.then((mapid) => initialize(mapid));
```
--------------------------------
### Map Container Styling
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-nodejs/index.html
Styles the container element for the map, setting its height, width, and background color.
```css
#map-container {
height: 400px;
width: 100%;
background-color: #eee;
}
```
--------------------------------
### Google Earth Engine Client Authentication
Source: https://github.com/google/earthengine-api/blob/master/demos/client-auth/static/index.html
This snippet demonstrates the basic setup for client-side authentication with the Google Earth Engine API. It shows how to initialize the Earth Engine library and retrieve information about an image.
```python
import ee
try:
ee.Initialize()
print('Earth Engine initialized successfully.')
# Example: Get information about an image
image_info = ee.Image(1).getInfo()
print('Image info:', image_info)
except ee.EEException as e:
print(f'Earth Engine initialization failed: {e}')
except Exception as e:
print(f'An unexpected error occurred: {e}')
```
--------------------------------
### Parameter Setup for BigQuery Export
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Sets up project-specific parameters including project ID, dataset ID, table ID, and region for exporting Earth Engine data to BigQuery.
```python
# @title Parameter Setup
# Replace the project id with your project.
project_id = "example-project" # @param {type:"string"}
dataset_id = "ee_export"
table_id = "ee_test"
table = dataset_id + "." + table_id
region = 'us'
table_path = project_id + "." + dataset_id + "." + table_id
print("Region: ",region)
print("Table Path: ",table_path)
```
--------------------------------
### Clone Earth Engine API Repository
Source: https://github.com/google/earthengine-api/blob/master/demos/interactive-classifier/README.md
Instructions to clone the Earth Engine API repository from GitHub to access demo code.
```bash
git clone https://github.com/google/earthengine-api.git
```
--------------------------------
### Deploy EE-based App Engine App
Source: https://github.com/google/earthengine-api/blob/master/demos/interactive-classifier/README.md
Reference to developer documentation for deploying Earth Engine applications on App Engine. Requires a Service Account for credentials.
```markdown
[deploy an EE-based App Engine app](https://developers.google.com/earth-engine/app_engine_intro#deploying-app-engine-apps-with-earth-engine)
```
--------------------------------
### Build Static Assets
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Builds the static assets for hosting the webpage in Cloud Storage or other static hosting providers.
```Bash
npm run build
```
--------------------------------
### Clone Earth Engine API Repository
Source: https://github.com/google/earthengine-api/blob/master/demos/export-to-drive/README.md
Clones the Earth Engine API repository from GitHub to your local machine.
```git
git clone https://github.com/google/earthengine-api.git
```
--------------------------------
### Clone Earth Engine API Repository
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-python/README.md
Clones the Google Earth Engine API repository from GitHub to your local machine. This is a prerequisite for accessing the demo code.
```bash
git clone https://github.com/google/earthengine-api.git
```
--------------------------------
### Clone Earth Engine API Repository
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-nodejs/README.md
Clones the Google Earth Engine API repository from GitHub to access demo code.
```git
git clone https://github.com/google/earthengine-api.git
```
--------------------------------
### Google Earth Engine API Reference
Source: https://github.com/google/earthengine-api/blob/master/javascript/README.md
Provides a comprehensive listing of all Earth Engine client classes and methods. This reference is essential for understanding the full capabilities of the API.
```APIDOC
Google Earth Engine API Reference:
This document provides a comprehensive listing of all Earth Engine client classes and methods. For detailed information on specific classes, methods, parameters, and return values, please refer to the official API documentation.
Key areas covered include:
- Data types and structures
- Core functionalities for geospatial data processing
- Algorithms and reducers
- Visualization and export capabilities
Example classes and modules:
- ee.Image
- ee.FeatureCollection
- ee.Join
- ee.Reducer
Refer to https://developers.google.com/earth-engine/apidocs for the complete API documentation.
```
--------------------------------
### Navigate to Export-to-Drive Demo Directory
Source: https://github.com/google/earthengine-api/blob/master/demos/export-to-drive/README.md
Changes the current directory to the export-to-drive demo within the cloned Earth Engine API repository.
```bash
cd ./earthengine-api/demos/export-to-drive/
```
--------------------------------
### Upload to Cloud Storage
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Uploads the built static files to a Google Cloud Storage bucket.
```Bash
gsutil copy -r ./static/* gs:///cloudfunctions-demo/
```
--------------------------------
### Initialize Google Maps API with API Key
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-nodejs/README.md
Initializes the Google Maps JavaScript API by including an API key in the index.html file. This is crucial for the interactive map functionality.
```javascript
// Example placeholder for API key initialization in index.html
// Replace YOUR_API_KEY with your actual Google Maps API key
//
```
--------------------------------
### Initialize EE Exporter
Source: https://github.com/google/earthengine-api/blob/master/demos/export-to-drive/index.html
Initializes the Earth Engine exporter with a channel token and client ID. This is a crucial step before any export operations can be performed.
```JavaScript
exporter.boot('{{ channelToken }}', '{{ clientId }}');
```
--------------------------------
### Make Cloud Storage Public
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Sets public read permissions for the uploaded demo files in Cloud Storage.
```Bash
gsutil -m acl set -R -a public-read gs:///cloudfunctions-demo/*
```
--------------------------------
### Authenticate and Initialize Earth Engine Session
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Authenticates the user with Google Cloud and initializes the Earth Engine API with the specified project credentials.
```python
# @title Authenticate and initialize the Session
import google
import ee
from google.cloud import bigquery
from google.colab import auth as google_auth
client= bigquery.Client()
google_auth.authenticate_user()
credentials, auth_project_id = google.auth.default()
ee.Initialize(credentials, project=project_id)
```
--------------------------------
### Earth Engine Image Overlay Demo
Source: https://github.com/google/earthengine-api/blob/master/demos/map-layer/static/index.html
This snippet shows how to create and add an Earth Engine image layer to a map using the ee.layers.ImageOverlay class. It assumes you have authenticated with Earth Engine and have a map object available.
```Python
import ee
import ee.mapclient
# Authenticate and initialize Earth Engine
try:
ee.Initialize()
except ee.EEException as e:
print('Earth Engine initialization failed: {}'.format(e))
# Handle authentication or initialization error
# Create a sample image (e.g., Sentinel-2 cloud-free composite)
image = ee.ImageCollection('COPERNICUS/S2_SR') \
.filterDate('2023-01-01', '2023-01-31') \
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20)) \
.median()
# Define visualization parameters
vis_params = {
'bands': ['B4', 'B3', 'B2'],
'min': 0,
'max': 3000,
'gamma': 1.4
}
# Create an ImageOverlay
image_overlay = ee.layers.ImageOverlay(image, vis_params)
# Add the overlay to a map (assuming 'map' is an existing map object)
# For example, if using geemap:
# import geemap
# Map = geemap.Map()
# Map.addLayer(image_overlay, {}, 'Sentinel-2 Composite')
# Map.centerObject(image, 8)
# If using a custom map object, the method to add the layer might differ.
# For demonstration purposes, we'll just print a confirmation.
print('ImageOverlay created. Add it to your map object.')
```
--------------------------------
### Deploy Cloud Function
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Deploys the script as a Google Cloud Function triggered by HTTP requests.
```Bash
gcloud beta functions deploy hexPopHttp --trigger-http --project --stage-bucket
```
--------------------------------
### Initialize Earth Engine Map with SRTM Data
Source: https://github.com/google/earthengine-api/blob/master/demos/server-auth-python/index.html
This JavaScript code snippet demonstrates how to initialize an Earth Engine map. It assumes that the Google Maps API has finished loading and uses provided `mapid` and `token` values, likely generated by a server-side script, to display map tiles. The `initialize` function is called with these credentials.
```javascript
var initMap = function() {
// The values of mapid and token for the map tiles, generated by Earth
// Engine using the Python script server.py, are injected here using
// the Jinja2 templating engine.
initialize('{{ mapid }}', '{{ token }}');
};
```
--------------------------------
### Deploy Earth Engine WMTS Proxy
Source: https://github.com/google/earthengine-api/blob/master/demos/wmts/README.md
Deploys the Earth Engine WMTS proxy application to Google App Engine. Requires the gcloud binary and an App Engine project ID.
```shell
chmod +x deploy.sh
./deploy.sh
```
--------------------------------
### Google Earth Engine API Reference
Source: https://github.com/google/earthengine-api/blob/master/python/README.md
Provides a comprehensive listing of all Earth Engine client classes and methods. This is the definitive reference for all available functionalities within the Earth Engine API.
```APIDOC
Google Earth Engine API Reference:
- Comprehensive listing of all Earth Engine client classes and methods.
- Refer to https://developers.google.com/earth-engine/apidocs for details.
```
--------------------------------
### Google Earth Engine API - Export Functionality
Source: https://github.com/google/earthengine-api/blob/master/demos/export-to-drive/index.html
This section outlines the core functionality for exporting Earth Engine data. It includes user interface elements for selecting export parameters like year and region, and initiating the export process.
```APIDOC
Export Functionality:
User Interface Elements:
- Year Selection Control: Allows users to choose a specific year for data export.
- Region Selection Control: Enables users to draw or select a polygon region on the map for data export. Includes options to 'Draw on the map', 'Cancel', 'Selected', and 'Clear'.
- Filename Control: Input field for specifying the name of the exported file.
- Export Button: Initiates the data export process.
Export Process:
- Upon clicking 'Export', a .TIF file is generated for the selected year and polygon.
Notifications:
- A notification area is present to display messages to the user.
```
--------------------------------
### Python Dependencies for Google Earth Engine API
Source: https://github.com/google/earthengine-api/blob/master/python/requirements.txt
Lists the required Python packages and their version constraints for interacting with the Google Earth Engine API.
```python
google-cloud-storage
google-api-python-client>=1.12.1
google-auth>=1.4.1
google-auth-httplib2>=0.0.3
httplib2>=0.9.2,<1dev
requests
```
--------------------------------
### Test Cloud Function Locally
Source: https://github.com/google/earthengine-api/blob/master/demos/cloud-functions/README.md
Tests the Cloud Function script locally to ensure it outputs GeoJSON without errors.
```Bash
npm test
```
--------------------------------
### Initialize Trendy Lights Demo
Source: https://github.com/google/earthengine-api/blob/master/demos/trendy-lights/index.html
Initializes the Trendy Lights demo with a map URL format and serialized polygon IDs. This function is part of the Google Earth Engine API demos.
```javascript
trendy.boot( '{{ mapUrlFormat | safe }}', '{{ serializedPolygonIds | safe }}');
```
--------------------------------
### Create BigQuery Dataset
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Creates a new BigQuery dataset within the specified GCP project and region.
```python
# @title Create BQ Dataset
# Create a BQ dataset.
!bq --location={region} mk --dataset {project_id}:{dataset_id}
```
--------------------------------
### Google Maps Image Overlay with Earth Engine
Source: https://github.com/google/earthengine-api/blob/master/demos/map-layer/README.md
This JavaScript code demonstrates how to create a map layer using ee.layers.ImageOverlay to render Earth Engine map tiles on a Google Map. It utilizes the google.maps.MapType interface and supports canceling obsolete tile requests and registering tile load callbacks.
```JavaScript
/**
* @fileoverview A demo showing how to use ee.layers.ImageOverlay to render
* Earth Engine map tiles on a Google Map.
*
* @suppress {missingRequire}
*/
google.maps.Map.prototype.setMapTypeId = function(mapTypeId) {
this.mapTypeId = mapTypeId;
};
/**
* Creates a new Map Layer Demo App.
* @param {!google.maps.Map} map The map to display.
* @constructor
*/
var MapLayerDemoApp = function(map) {
this.map = map;
// Create an Earth Engine image. This example uses a Landsat 8 image.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044030_20140318')
.select(['B4', 'B3', 'B2']);
// Create an Earth Engine map overlay.
var eeOverlay = new ee.layers.ImageOverlay(image, {
// Define the projection and transform for the overlay.
// This is necessary for Earth Engine images.
projection: image.projection().getInfo(),
transform: image.projection().transform().getInfo(),
// Set the opacity of the overlay.
opacity: 0.7,
// Set the name of the overlay.
name: 'Landsat 8 SR'
});
// Add the Earth Engine overlay to the map.
eeOverlay.setMap(map);
// Add a listener for when the map is clicked.
map.addListener('click', this.handleMapClick.bind(this));
};
/**
* Handles map click events.
* @param {!google.maps.MouseEvent} mouseEvent The mouse event.
*/
MapLayerDemoApp.prototype.handleMapClick = function(mouseEvent) {
console.log('Map clicked at:', mouseEvent.latLng.toString());
};
/**
* Initializes the map and the MapLayerDemoApp.
*/
function initMap() {
var mapOptions = {
center: {lat: 37.7749, lng: -122.4194},
zoom: 10,
mapTypeId: 'satellite'
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var app = new MapLayerDemoApp(map);
}
```
--------------------------------
### Display Flooded Areas and Highways using geemap
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Visualizes both the flooded areas and the roads intersecting with them on an interactive map using the geemap library. It loads the GeoJSON data, applies styling, and adds the layers to the map.
```Python
# @title Display Flooded Areas and Highways using geemap
import geemap
from ipyleaflet import GeoJSON
import json
styling = {"color": "red", "fillcolor": "red"}
flooded_areas = GeoJSON(
data=json.loads(floods),
name='Flooded areas'
)
flooded_highways = GeoJSON(
data=json.loads(highways),
name='Flooded roads',
style=styling
)
Map=geemap.Map()
Map.setOptions(mapTypeId = 'HYBRID', styles = {}, types = [])
Map.centerObject(aoi, 12)
Map.add_layer(flooded_areas)
Map.add_layer(flooded_highways)
Map
```
--------------------------------
### Visualize Flooded Areas
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Visualizes the processed flooded areas on a map using the geemap library. It sets map options, centers the map on a specified area of interest (aoi), and adds a layer for the flooded areas.
```Python
# @title Visualize the Map with Flooded Area
# Display flooded areas on the map.
import geemap
vis_params = {
"palette": ["blue"],
}
Map = geemap.Map()
Map.setOptions(mapTypeId='HYBRID', styles={}, types=[])
Map.centerObject(aoi, 12);
Map.addLayer(
diff_thresholded.updateMask(diff_thresholded),
vis_params,
'flooded areas - blue',
True)
Map
```
--------------------------------
### Load and Process Sentinel-1 Data
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Loads Sentinel-1 SAR data, filters it by AOI and polarization (VV), applies a median filter for smoothing, and separates data into 'before' and 'after' flood periods.
```python
# @title Data Collections
# Load Sentinel-1 C-band SAR Ground Range collection (log scaling, VV co-polar).
collection = ee.ImageCollection('COPERNICUS/S1_GRD') \
.filterBounds(aoi) \
.filter(ee.Filter.listContains('transmitterReceiverPolarisation', 'VV')) \
.select('VV')
# Smooth the data to remove noise.
smoothing_radius = 100 # meters
# Filter by date.
before = collection.filterDate('2017-11-01', '2017-11-17') \
.mosaic() \
.focal_median(smoothing_radius, 'circle', 'meters') # before floods
after = collection.filterDate('2017-11-18', '2017-11-23') \
.mosaic() \
.focal_median(smoothing_radius, 'circle', 'meters') # after floods
```
--------------------------------
### Display AOI and Map
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Visualizes the defined Area of Interest (AOI) on an interactive map and sets map options for better visualization.
```python
# @title Display AOI and point
import geemap
Map = geemap.Map()
Map.centerObject(aoi, 12);
Map.setOptions(mapTypeId='HYBRID', styles={}, types=[])
Map.addLayer(aoi, {"color":"blue"});
Map
```
--------------------------------
### Identify Flooded Areas
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Identifies potential flooded areas by calculating the difference between 'after' and 'before' radar intensities and applying a threshold to detect areas with standing water.
```python
# @title Identify Flooded Areas
# Threshold smoothed radar intensities to identify areas with standing water.
diff_upper_threshold = -3 # dB
diff_smoothed = after.subtract(before);
diff_thresholded = diff_smoothed.lt(diff_upper_threshold)
```
--------------------------------
### Process JRC GSW Data
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Processes the JRC Global Surface Water dataset to identify water occurrences and mask out non-water areas. It selects the 'occurrence' band and applies a threshold based on metadata.
```Python
jrc_data0 = ee.Image("JRC/GSW1_0/Metadata") \
.select('total_obs') \
.lte(0)
water_occ = ee.Image("JRC/GSW1_0/GlobalSurfaceWater") \
.select('occurrence') \
.unmask(0) \
.max(jrc_data0) \
.lt(10)
diff_thresholded = diff_thresholded.updateMask(water_occ)
```
--------------------------------
### Compute Night-time Lights Trend (JavaScript)
Source: https://github.com/google/earthengine-api/blob/master/README.md
Computes the trend of night-time lights using the NOAA DMSP-OLS NIGHTTIME LIGHTS dataset. It adds a band containing the image date as years since 1991 and then computes a linear fit over the series of values at each pixel, visualizing the y-intercept and slopes.
```javascript
// Compute the trend of night-time lights.
// Adds a band containing image date as years since 1991.
function createTimeBand(img) {
var year = ee.Date(img.get('system:time_start')).get('year').subtract(1991);
return ee.Image(year).byte().addBands(img);
}
// Map the time band creation helper over the night-time lights collection.
// https://developers.google.com/earth-engine/datasets/catalog/NOAA_DMSP-OLS_NIGHTTIME_LIGHTS
var collection = ee.ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS')
.select('stable_lights')
.map(createTimeBand);
// Compute a linear fit over the series of values at each pixel, visualizing
// the y-intercept in green, and positive/negative slopes as red/blue.
Map.addLayer(
collection.reduce(ee.Reducer.linearFit()),
{min: 0, max: [0.18, 20, -0.18], bands: ['scale', 'offset', 'scale']},
'stable lights trend');
```
--------------------------------
### Export Flooded Area Vectors to BigQuery
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Exports the extracted vector data of flooded areas to a BigQuery table. This function utilizes the Earth Engine batch export functionality. It configures the export task with the vector data, a description, and the target BigQuery table path.
```Python
# @title Export to BigQuery
task_config = {
'collection': vectors,
'description':'ee2bq_export_polygons',
'table': table_path
}
task = ee.batch.Export.table.toBigQuery(**task_config)
task.start()
# The task should run for about a minute. Check task.status() to see the result.
```
--------------------------------
### Define Area of Interest (AOI)
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Defines a polygonal Area of Interest (AOI) for data filtering and analysis in Earth Engine.
```python
# @title Define point and Area of Interest(aoi)
# Define AOI (Area of Interest) polygon
aoi = ee.Geometry.Polygon([[-2.92, 54.10],
[-2.92, 53.99],
[-2.67, 53.99],
[-2.67, 54.10]])
```
--------------------------------
### Check Export Job Status
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Checks the status of an ongoing Earth Engine export task. This is crucial to ensure the data has been successfully exported to BigQuery before attempting to query it.
```Python
# @title Check Export Job Status
# Check the results and make sure the status is COMPLETED before checking the
# results in BigQuery.
task.status()
```
--------------------------------
### Query BigQuery for Flooded Areas and Intersecting Highways
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Queries BigQuery to retrieve flooded areas and join them with road data from OpenStreetMap. It filters out large administrative areas, selects road geometries, and uses spatial functions to find intersections. The results include flood polygon geometry, area, and road details.
```SQL
# @title BQ Result set to display flooded highways
%%bigquery regions_by_country --project $project_id
SELECT
id, area,version,changeset,osm_timestamp,ST_ASGEOJSON(flood_poly) as flood_poly,
ST_ASGEOJSON(road_geometry) as road_geometry
FROM (
-- query 1 - find all the flooding areas
SELECT
geo AS flood_poly,
ST_AREA(geo) AS area
FROM
ee_export.ee_test
WHERE
ST_AREA(geo) < 500000 ) t1 -- eliminate admin areas in the dataset
JOIN (
SELECT
id,
version,
changeset,
osm_timestamp,
geometry as road_geometry
FROM
`bigquery-public-data.geo_openstreetmap.planet_ways` planet_ways,
planet_ways.all_tags AS all_tags
WHERE
all_tags.key = 'highway' )
ON
ST_INTERSECTS(flood_poly, road_geometry)
```
--------------------------------
### Extract GeoJSON Features for Flooded Areas
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Extracts the GeoJSON representations of flood polygons from the BigQuery results and formats them into a GeoJSON FeatureCollection string. This prepares the data for visualization.
```Python
# @title Extract the Features from flood_poly
floods = '{"type": "FeatureCollection", "features":['
floods += regions_by_country.flood_poly.str.cat(sep=", ")
floods += ']}'
```
--------------------------------
### Extract GeoJSON Features for Flooded Highways
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Extracts the GeoJSON representations of road geometries that intersect with flooded areas from the BigQuery results. It formats these into a GeoJSON FeatureCollection string for subsequent mapping.
```Python
# @title Extract the features from road_geometry
highways = '{"type": "FeatureCollection", "features":['
highways += regions_by_country.road_geometry.str.cat(sep=", ")
highways += ']}'
```
--------------------------------
### Extract Vectors from Flooded Areas
Source: https://github.com/google/earthengine-api/blob/master/demos/flooded-roads/ExportToBigQuery.ipynb
Converts the raster data of flooded areas into vector polygons. This is useful for exporting to vector-based data stores like BigQuery. It specifies the geometry type, scale, and connectivity.
```Python
# @title Extract Vectors from the Flooded areas
# Extract vectors from the diff threshold to load to BigQuery.
vectors = diff_thresholded.reduceToVectors(
geometry = aoi,
scale = 10,
geometryType = 'polygon',
eightConnected = False)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.