Learn how to integrate ObservEarth APIs with common GIS tools, data science platforms, and web applications.
QGIS is a powerful open-source Geographic Information System that can be integrated with ObservEarth APIs for advanced spatial analysis.
from qgis.core import QgsProject, QgsRasterLayer
import requests
import os
# Set your API key
api_key = "your_api_key_here"
geometry_id = "123e4567-e89b-12d3-a456-426614174000"
# Get NDVI image
url = f"https://observearth.com/api/s2/image/{geometry_id}/"
params = {
"item_id": "S2A_MSIL2A_20230105T123456_N0509_R123_T18TXM_20230105T150000",
"image_type": "tiff",
"index": "ndvi"
}
headers = {"X-API-Key": api_key}
# Download the GeoTIFF
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
# Save the file
output_path = "/tmp/ndvi_image.tif"
with open(output_path, "wb") as f:
f.write(response.content)
# Add to QGIS
layer_name = "NDVI Layer"
rlayer = QgsRasterLayer(output_path, layer_name)
if rlayer.isValid():
QgsProject.instance().addMapLayer(rlayer)
print("Layer added successfully!")
else:
print("Invalid layer!")
[Image: Screenshot of QGIS with ObservEarth data loaded]
QGIS interface showing NDVI data loaded from ObservEarth API.
For more advanced integration, you can create a custom QGIS plugin that provides a user interface for accessing ObservEarth data directly within QGIS.
ArcGIS users can integrate ObservEarth data using Python and the ArcPy library:
import arcpy
import requests
import os
# Set your API key
api_key = "your_api_key_here"
geometry_id = "123e4567-e89b-12d3-a456-426614174000"
# Get DEM data
url = f"https://observearth.com/api/dem/"
params = {
"geometry_id": geometry_id,
"format": "geotiff",
"source": "srtm"
}
headers = {"X-API-Key": api_key}
# Download the GeoTIFF
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
# Save the file
output_path = r"C:\temp\dem_data.tif"
with open(output_path, "wb") as f:
f.write(response.content)
# Set up the environment
arcpy.env.workspace = r"C:\temp"
# Create a hillshade
hillshade = arcpy.sa.Hillshade(output_path,
azimuth=315,
altitude=45,
model_shadows="NO_SHADOWS")
hillshade.save(r"C:\temp\hillshade.tif")
# Create contours
contour_interval = 50
contours = r"C:\temp\contours.shp"
arcpy.sa.Contour(output_path, contours, contour_interval)
print("Processing complete!")
[Image: Screenshot of ArcGIS Pro with ObservEarth data]
ArcGIS Pro showing DEM data and derived products from ObservEarth API.
Jupyter Notebooks provide an excellent environment for interactive analysis of ObservEarth data:
Check out our sample Jupyter notebooks for common analysis workflows.
While Google Earth Engine (GEE) has its own data catalog, you can enhance your GEE workflows by integrating ObservEarth data:
import ee
import requests
import numpy as np
import matplotlib.pyplot as plt
from io import BytesIO
# Initialize Earth Engine
ee.Initialize()
# Set your ObservEarth API key
api_key = "your_api_key_here"
geometry_id = "123e4567-e89b-12d3-a456-426614174000"
# Get geometry from ObservEarth
url = f"https://observearth.com/api/geometry/{geometry_id}/"
headers = {"X-API-Key": api_key}
response = requests.get(url, headers=headers)
geom_data = response.json()
# Convert to Earth Engine geometry
coords = geom_data["geometry"]["coordinates"][0]
ee_polygon = ee.Geometry.Polygon(coords)
# Load Landsat imagery in Earth Engine
landsat = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2') \
.filterBounds(ee_polygon) \
.filterDate('2020-01-01', '2020-12-31') \
.sort('CLOUD_COVER') \
.first()
# Calculate NDVI in Earth Engine
nir = landsat.select('SR_B5')
red = landsat.select('SR_B4')
ndvi = nir.subtract(red).divide(nir.add(red)).rename('NDVI')
# Compare with ObservEarth NDVI
oe_url = f"https://observearth.com/api/landsat/stats/"
oe_payload = {
"geometry_id": geometry_id,
"start_date": "2020-01-01",
"end_date": "2020-12-31",
"cloud_cover": 20,
"index": "ndvi"
}
oe_response = requests.post(oe_url, headers=headers, data=json.dumps(oe_payload))
oe_data = oe_response.json()
# Now you can compare results from both sources
[Image: Side-by-side comparison of GEE and ObservEarth results]
Comparison of NDVI results from Google Earth Engine and ObservEarth for the same area.
Integrate ObservEarth data into web mapping applications using libraries like Leaflet or OpenLayers:
<!DOCTYPE html>
<html>
<head>
<title>ObservEarth with Leaflet</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<style>
#map { height: 600px; }
</style>
</head>
<body>
<div id="map"></div>
<script>
// Initialize map
const map = L.map('map').setView([51.505, -0.09], 13);
// Add base layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// ObservEarth API key
const apiKey = 'your_api_key_here';
const geometryId = '123e4567-e89b-12d3-a456-426614174000';
// Function to load NDVI overlay
async function loadNdviOverlay() {
// First get the geometry to center the map
const geomResponse = await fetch(
`https://observearth.com/api/geometry/${geometryId}/`,
{ headers: { 'X-API-Key': apiKey } }
);
const geomData = await geomResponse.json();
// Center map on the geometry
const coords = geomData.geometry.coordinates[0];
const bounds = coords.map(coord => [coord[1], coord[0]]);
map.fitBounds(bounds);
// Add geometry outline
L.polygon(bounds, {color: 'blue', weight: 2}).addTo(map);
// Create NDVI overlay URL
const ndviUrl = `https://observearth.com/api/s2/image/${geometryId}/?` +
`item_id=S2A_MSIL2A_20230105T123456_N0509_R123_T18TXM_20230105T150000&` +
`image_type=png&index=ndvi&colormap=RdYlGn`;
// Add NDVI as an overlay
fetch(ndviUrl, {
headers: { 'X-API-Key': apiKey }
})
.then(response => response.blob())
.then(blob => {
const imageUrl = URL.createObjectURL(blob);
const imageBounds = L.latLngBounds(bounds);
L.imageOverlay(imageUrl, imageBounds, {
opacity: 0.7
}).addTo(map);
});
}
// Load the NDVI overlay
loadNdviOverlay();
</script>
</body>
</html>
[Image: Screenshot of a web mapping application with ObservEarth data]
Web mapping application showing NDVI data from ObservEarth overlaid on a base map.
Create interactive dashboards with tools like Dash, Streamlit, or Tableau:
import streamlit as st
import requests
import pandas as pd
import plotly.express as px
import json
from datetime import datetime, timedelta
st.title("ObservEarth Vegetation Monitor")
# API key input (in a real app, use more secure methods)
api_key = st.sidebar.text_input("API Key", type="password")
# Get list of AOIs
if api_key:
@st.cache_data(ttl=3600)
def get_aois(api_key):
url = "https://observearth.com/api/geometry/"
headers = {"X-API-Key": api_key}
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()["results"]
else:
st.error(f"Error: {response.status_code}")
return []
aois = get_aois(api_key)
aoi_names = [aoi["name"] for aoi in aois]
aoi_ids = [aoi["id"] for aoi in aois]
# AOI selection
selected_aoi_name = st.sidebar.selectbox("Select Area of Interest", aoi_names)
selected_aoi_id = aoi_ids[aoi_names.index(selected_aoi_name)]
# Date range selection
end_date = datetime.now()
start_date = end_date - timedelta(days=365)
date_range = st.sidebar.date_input(
"Date Range",
[start_date, end_date]
)
# Index selection
index = st.sidebar.selectbox(
"Vegetation Index",
["ndvi", "evi", "ndmi", "ndwi", "lai"]
)
# Get data button
if st.sidebar.button("Get Data"):
with st.spinner("Fetching data..."):
# Get statistics
stats_url = "https://observearth.com/api/s2/stats/"
payload = {
"geometry_id": selected_aoi_id,
"start_date": date_range[0].strftime("%Y-%m-%d"),
"end_date": date_range[1].strftime("%Y-%m-%d"),
"cloud_cover": 20,
"index": index
}
headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
response = requests.post(stats_url, headers=headers, data=json.dumps(payload))
if response.status_code == 200:
data = response.json()
# Create dataframe
results = data["results"]
df = pd.DataFrame(results)
# Display summary statistics
st.subheader("Summary Statistics")
col1, col2, col3 = st.columns(3)
col1.metric("Average", f"{df['mean_value'].mean():.2f}")
col2.metric("Minimum", f"{df['min_value'].min():.2f}")
col3.metric("Maximum", f"{df['max_value'].max():.2f}")
# Plot time series
st.subheader("Time Series")
fig = px.line(df, x="date", y="mean_value",
title=f"{index.upper()} Time Series for {selected_aoi_name}")
st.plotly_chart(fig)
# Display latest image
st.subheader("Latest Image")
if len(results) > 0:
latest = results[-1]
image_url = f"https://observearth.com/api/s2/image/{selected_aoi_id}/"
params = {
"item_id": latest["id"],
"image_type": "png",
"index": index,
"colormap": "RdYlGn"
}
img_response = requests.get(image_url, headers={"X-API-Key": api_key}, params=params)
if img_response.status_code == 200:
st.image(img_response.content, caption=f"Latest {index.upper()} image ({latest['date']})")
else:
st.error(f"Error: {response.status_code}")
else:
st.warning("Please enter your API key to continue")
[Image: Screenshot of a Streamlit dashboard using ObservEarth data]
Interactive Streamlit dashboard for monitoring vegetation health using ObservEarth APIs.
Now that you understand how to integrate ObservEarth APIs with various tools and platforms, you can: