Skip to main content
03 // ENGINEERING SPECIFICATIONTop 300 Best Project Winner — OregonHacks 2026

MossMap: Citizen-Science Bioindicator Vision & Hyper-Local Ecosystem Health Mapping

A Top 300 Best Project Winner submission built for OregonHacks 2026 (Nature + Tech track) that turns everyday smartphones into bryological and lichenological air-quality sensors—combining HTML5 Canvas camera capture, Gemini Vision stress-indicator decomposition, dual-mode Supabase + in-memory persistence, and an interactive React-Leaflet geospatial health map.

Published 2026-09-20Updated 2026-09-229 min readGitHub Repository
Next.js 15React 19TypeScriptGemini Vision APIReact-LeafletSupabase PostgreSQLTailwind CSS v4

1. Overview#

MossMap is a citizen-science bioindicator and geospatial health mapping web application—recognized as a Top 300 Best Project Winner Submission (built for the OregonHacks 2026 Nature + Tech track)—that turns smartphone photographs of Pacific Northwest mosses and lichens into structured environmental stress and air-quality observations.

Because bryophytes (mosses and liverworts) and lichens lack root systems and protective cuticles, they absorb moisture and atmospheric compounds directly across their surface. Species such as Lobaria pulmonaria (Lungwort Lichen), Lobaria oregana, and Kindbergia oregana (Oregon Beaked Moss) exhibit visible morphological responses—lobe bleaching, tip browning, fragmentation, and shriveling—when exposed to elevated $\text{SO}_2$, $\text{NO}_x$, nitrogen enrichment, or microclimate drying.

MossMap guides users through a four-stage workflow:

  1. Guided Specimen Capture (`src/components/camera-capture.tsx`): Mobile-first MediaStream camera preview with a framing reticle overlay (1280x1280 ideal resolution) and HTML5 <canvas> JPEG extraction, plus file upload support.
  2. Multimodal Bioindicator Analysis (`/api/analyze` & `src/lib/ai.ts`): Sends the specimen image to Gemini Vision (responseMimeType: "application/json") to identify Pacific Northwest taxa (species_common, species_scientific, confidence) and quantify three environmental sub-scores (moisture_stress, pollution_indicators, canopy_estimate) alongside an overall stress_score (0–100) and inverted health_score (100 - stress_score).
  3. Ecological Context & Micro-Actions (`src/components/results-card.tsx`): Surfaces species-specific ecological roles, Oregon/PNW habitat relevance, and concrete conservation micro-actions.
  4. Hyper-Local Nature Health Map (`/map` & `src/components/nature-map.tsx`): Plots anonymized community observations onto a CARTO Dark Matter React-Leaflet basemap with color-graded CircleMarker health pins and temporal window filters (24h, 7d, 30d, all).

2. The Problem#

Environmental monitoring across urban greenspaces and regional forests faces three practical limitations:

  • Sparse physical air-quality sensors: Municipal air-quality monitoring stations are expensive and separated by miles, missing hyper-local pollution corridors near highways, industrial edges, or heat-island pockets.
  • High expertise barrier for bioindicator field surveys: While bryologists and forest service ecologists use epiphytic lichens (Lobaria, Letharia) and forest-floor mosses (Hylocomium, Kindbergia) to assess air quality and humidity regimes, everyday hikers and students cannot distinguish pollution bleaching from seasonal dormancy or identify PNW taxa in the field.
  • Taxonomy-only citizen science apps: Existing platforms like iNaturalist excel at cataloging where a species was seen, but do not quantify visual physiological stress indicators (browning, bleaching, canopy openness) into a real-time ecosystem health index.

3. The Approach#

MossMap was architected around four pragmatic engineering decisions:

  1. Structured Visual Stress Decomposition + Numeric Clamping: Rather than asking an LLM for a vague qualitative health opinion, SYSTEM_PROMPT in src/lib/ai.ts instructs Gemini Vision (temperature: 0.2, responseMimeType: "application/json") to evaluate three distinct visual axes—moisture_stress (dryness, browning, shriveling), pollution_indicators (bleaching, soot, lobe damage), and canopy_estimate (light exposure)—before computing stress_score. Every numeric field is deterministically clamped to [0, 1] or [0, 100] after JSON parsing.
  2. Zero-Dead-End Dual-Mode Persistence (`src/lib/supabase.ts`): Live hackathon judges and offline field testers frequently run without database credentials or hit intermittent network drops. fetchObservations() and saveObservation() read and write to Supabase PostgreSQL (public.observations) when configured, and automatically fall back to an in-memory store pre-seeded with 8 geographically accurate Oregon observations (SAMPLE_OBSERVATIONS across Portland, Salem, Bend, and the Cascades).
  3. Client-Only Leaflet Hydration Guard (`src/components/nature-map.tsx`): Because leaflet directly accesses window and document on module evaluation, NatureMap renders an accessible emerald skeleton placeholder during Next.js Server-Side Rendering (SSR) and dynamically imports leaflet inside useEffect once mounted in the browser.
  4. Privacy-Preserving One-Tap Contribution: Observations default to anonymous submissions (with optional user-chosen nicknames) and fall back to Portland coordinates (45.5152, -122.6784) if browser geolocation permission is declined.

4. System Architecture#

MossMap is structured as a Next.js 15 App Router + React 19 application with two primary API routes (/api/analyze and /api/observations), a multimodal AI service layer, and a dual-mode Supabase/in-memory geospatial store.

SYSTEM SCHEMATIC // MOSSMAP BIOINDICATOR VISION PIPELINE & GEOSPATIAL HEALTH MAPPING ARCHITECTURE
01. Client Capture & Geospatial Visualization Layer (React 19 · Next.js 15)
MediaStream & Canvas Capture

1280x1280 environment camera stream with reticle overlay and 0.92 JPEG blob serialization

src/components/camera-capture.tsx
Bioindicator Scorecard (/results)

Displays taxonomic ID, confidence, moisture/pollution/canopy bars, and PNW micro-actions

src/components/results-card.tsx
Interactive Nature Health Map (/map)

SSR-safe React-Leaflet map with health-graded CircleMarkers and 24h/7d/30d/all filters

src/components/nature-map.tsx · CARTO Dark
Multipart FormData (/api/analyze) & JSON REST (/api/observations)
02. Next.js App Router API & Multimodal Vision Layer
Vision Analysis Endpoint (/api/analyze)

Extracts image buffer + GPS coordinates, invokes analyzeImage(), and computes health_score = 100 - stress_score

src/app/api/analyze/route.ts · maxDuration=30s
Bryological Vision Analyzer

Prompts Gemini Vision for PNW species ID + 3-axis stress scores, clamps bounds, and provides offline fallback

src/lib/ai.ts · @google/generative-ai
Observations API (/api/observations)

Validates required taxonomic/geospatial fields on POST and filters by timeRange on GET

src/app/api/observations/route.ts
JSON-Constrained Vision Inference & Dual-Store Queries
03. Dual-Mode Persistence Layer
Supabase PostgreSQL (public.observations)

Stores coordinates, species, stress breakdown, ecological notes, and timestamps under public RLS policies

src/lib/supabase.ts · @supabase/supabase-js
In-Memory Fallback & PNW Seed Corpus

8 curated Oregon observations (Kindbergia oregana, Lobaria pulmonaria, Letharia vulpina, etc.)

src/data/sample-observations.ts
Figure: MossMap Bioindicator Vision Pipeline & Geospatial Health Mapping Architecture

5. Engineering Deep Dive#

5.1 Environment Camera Capture & Offscreen Canvas Serialization (`src/components/camera-capture.tsx`)#

To capture consistent macro images of tree bark and forest-floor moss beds on mobile devices, CameraCapture requests the rear camera at an ideal 1280x1280 square aspect ratio (facingMode: { ideal: "environment" }), overlays a circular framing guide, and draws the live <video> frame onto an offscreen <canvas> before releasing all hardware camera tracks:

src/components/camera-capture.tsxtsx
const startCamera = useCallback(async () => {
  setError(null);
  setStarting(true);
  try {
    const media = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: { ideal: "environment" },
        width: { ideal: 1280 },
        height: { ideal: 1280 },
      },
      audio: false,
    });
    setCameraActive(true);
    setStream(media);
  } catch (err) {
    console.error(err);
    setError("Camera access denied or unavailable. You can still upload a photo.");
  } finally {
    setStarting(false);
  }
}, []);

const takePhoto = useCallback(() => {
  const video = videoRef.current;
  if (!video || !video.videoWidth || !video.videoHeight) {
    setError("Camera is still warming up. Try again in a moment.");
    return;
  }

  const canvas = document.createElement("canvas");
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  const ctx = canvas.getContext("2d");
  if (!ctx) return;
  ctx.drawImage(video, 0, 0);

  canvas.toBlob(
    (blob) => {
      if (!blob) return;
      const file = new File([blob], `moss-${Date.now()}.jpg`, { type: "image/jpeg" });
      const url = URL.createObjectURL(blob);
      stopCamera();
      onCapture(file, url);
    },
    "image/jpeg",
    0.92
  );
}, [onCapture, stopCamera]);

5.2 JSON-Constrained Bryological Vision Analysis & Numeric Clamping (`src/lib/ai.ts`)#

In src/lib/ai.ts, analyzeImage() strips any data:image/...;base64, prefix, passes the image buffer alongside SYSTEM_PROMPT to Gemini with responseMimeType: "application/json" and temperature: 0.2, and clamps every returned score to prevent out-of-range UI progress bars:

src/lib/ai.tstypescript
export async function analyzeImage(
  imageBase64: string,
  mimeType: string = "image/jpeg"
): Promise<AnalysisResult> {
  const apiKey = process.env.GOOGLE_GEMINI_API_KEY;

  if (!apiKey) {
    await new Promise((r) => setTimeout(r, 1800));
    return getMockAnalysis();
  }

  try {
    const genAI = new GoogleGenerativeAI(apiKey);
    const model = genAI.getGenerativeModel({
      model: "gemini-1.5-flash",
      generationConfig: {
        temperature: 0.2,
        maxOutputTokens: 1024,
        responseMimeType: "application/json",
      },
    });

    const result = await model.generateContent([
      { text: SYSTEM_PROMPT },
      {
        inlineData: {
          mimeType,
          data: imageBase64.replace(/^data:image\/\w+;base64,/, ""),
        },
      },
    ]);

    const parsed = JSON.parse(result.response.text()) as AnalysisResult;

    // Deterministic numeric clamping to [0, 1] and [0, 100]
    parsed.confidence = Math.max(0, Math.min(1, parsed.confidence ?? 0.5));
    parsed.stress_score = Math.max(0, Math.min(100, parsed.stress_score ?? 50));
    parsed.moisture_stress = Math.max(0, Math.min(100, parsed.moisture_stress ?? 50));
    parsed.pollution_indicators = Math.max(0, Math.min(100, parsed.pollution_indicators ?? 50));
    parsed.canopy_estimate = Math.max(0, Math.min(100, parsed.canopy_estimate ?? 50));
    if (!Array.isArray(parsed.micro_actions)) parsed.micro_actions = [];

    return parsed;
  } catch (err) {
    console.error("Gemini analysis failed, falling back to mock:", err);
    return getMockAnalysis();
  }
}

5.3 Dual-Mode Time-Windowed Observation Store (`src/lib/supabase.ts`)#

fetchObservations() computes an ISO-8601 cutoff timestamp for 24h, 7d, and 30d temporal filters and executes a .gte("timestamp", cutoff) query against Supabase PostgreSQL, falling back transparently to filterMemory(filter) if the database client is unconfigured or returns a network error:

src/lib/supabase.tstypescript
export async function fetchObservations(filter: {
  timeRange?: "24h" | "7d" | "30d" | "all";
} = {}): Promise<Observation[]> {
  if (supabase) {
    let query = supabase
      .from("observations")
      .select("*")
      .order("timestamp", { ascending: false });

    if (filter.timeRange && filter.timeRange !== "all") {
      const now = Date.now();
      const ms =
        filter.timeRange === "24h"
          ? 24 * 60 * 60 * 1000
          : filter.timeRange === "7d"
            ? 7 * 24 * 60 * 60 * 1000
            : 30 * 24 * 60 * 60 * 1000;
      const cutoff = new Date(now - ms).toISOString();
      query = query.gte("timestamp", cutoff);
    }

    const { data, error } = await query;
    if (error) {
      console.error("Supabase fetch error:", error);
      return filterMemory(filter);
    }
    return (data as Observation[]) ?? [];
  }

  return filterMemory(filter);
}

5.4 Health-Graded Geospatial Rendering (`src/components/nature-map.tsx`)#

On the map view, each observation's health_score (100 - stress_score) maps to a four-tier semantic color scale—Emerald (#10b981, $\ge 75$), Lime (#84cc16, $\ge 50$), Amber (#f59e0b, $\ge 30$), and Rose (#f43f5e, $< 30$)—rendered as interactive CircleMarker vectors with expanded selection radii (radius: isSelected ? 12 : 8).

6. Technical Demo#

Technical Walkthrough & Verification
Recorded video walkthrough coming soon

Technical walkthrough recording coming soon

Walkthrough of MossMap's mobile MediaStream + Canvas specimen capture, Gemini Vision bioindicator stress decomposition (moisture, pollution, canopy), and real-time Pacific Northwest health mapping.

Walkthrough Sequence & Checkpoints

  1. 00:00
    Mosses & Lichens as Living Air-Quality Bioindicators — Why rootless bryophytes and cyanolichens (Kindbergia oregana, Lobaria pulmonaria) reflect hyper-local SO2, NOx, and moisture stress.
  2. 00:45
    MediaStream Reticle Capture & Offscreen Canvas Encoding — Capturing 1280x1280 environment-camera frames in src/components/camera-capture.tsx and serializing 0.92-quality JPEG blobs.
  3. 01:40
    Gemini Vision Taxonomic ID & Stress Decomposition — Inspecting /api/analyze and src/lib/ai.ts as they extract species confidence, moisture stress, pollution indicators, and canopy estimates.
  4. 02:35
    Dual-Mode Persistence & React-Leaflet Health Map — Contributing anonymized observations to Supabase (with seeded PNW memory fallback) and filtering 24h/7d/30d pins on the CARTO dark basemap.
View Written Walkthrough Summary / Transcript ▾

Mosses and lichens have no roots or protective cuticles—they absorb water, nitrogen oxides, sulfur dioxide, and heavy metals directly from the air. That makes them living, block-by-block sensors of air quality and forest microclimate.

Built for the Nature + Tech track at OregonHacks 2026 and recognized as a Top 300 Best Project Winner submission, MossMap lets hikers, students, and park rangers photograph any Pacific Northwest moss or lichen and convert it into a structured ecological health reading.

The pipeline captures a square 1280x1280 frame via MediaStream and HTML5 Canvas, runs a JSON-constrained Gemini Vision analysis that scores moisture stress, pollution bleaching, and canopy cover, clamps all numeric ranges, and plots the resulting health score onto a time-filterable React-Leaflet map.

7. Challenges and Trade-offs#

  • Visual Bioindicator Estimation vs. Laboratory Assay: A smartphone photograph can detect macro-level morphological symptoms (lobe bleaching on Lobaria, tip desiccation on Hylocomium, canopy openness), but cannot measure exact parts-per-billion $\text{SO}_2$ concentrations. Framing the output as a relative Environmental Stress Score (`0–100`) with explicit confidence bounds keeps the citizen-science signal honest and actionable.
  • React 19 + React-Leaflet 5 SSR Compatibility: leaflet mutates DOM globals on import, which breaks Next.js App Router server pre-rendering if imported eagerly. Guarding the map behind a client mounted state and dynamic import("leaflet") avoided hydration mismatches while keeping initial page transitions fast.
  • Anonymous Contribution vs. Spam Prevention: Allowing zero-login anonymous INSERTs via Supabase RLS maximized citizen participation during the hackathon, at the cost of requiring stricter rate-limiting and image verification before opening the database to untrusted public traffic at scale.

8. Testing and Validation#

  • Pacific Northwest Taxonomic Seed Validation: Verified end-to-end rendering, temporal filtering (24h, 7d, 30d, all), and health-color grading across 8 distinct Oregon bioindicator profiles (Kindbergia oregana, Lobaria pulmonaria, Isothecium stoloniferum, Hylocomium splendens, Lobaria oregana, Polytrichum commune, Dicranum scoparium, and Letharia vulpina).
  • Graceful Degradation Testing: Verified /api/analyze and /api/observations across three environment configurations: full Gemini + Supabase credentials, Gemini-only with in-memory persistence, and zero-key offline demo mode.
  • Known Limitations: Uploaded photos are currently analyzed in memory via FormData buffers rather than persisted to a Supabase Storage bucket, and map rendering uses discrete CircleMarker pins rather than a continuous kernel-density heatmap layer.

9. What I Learned#

  • Domain-Specific Prompt Decomposition Produces Better Vision Metrics: Asking a vision model for a single "health score" yields noisy guesses; asking it to first inspect moisture browning, pollution bleaching, and canopy light separately before computing a composite score produces grounded, explainable outputs.
  • Seeded Dual-Mode Stores Make Geospatial Apps Immediately Testable: Geospatial citizen-science apps suffer from the "empty map problem" on first launch. Pairing Supabase with a realistic regional seed corpus (SAMPLE_OBSERVATIONS) made the spatial filtering and clustering mechanics immediately demonstrable.

10. Future Improvements#

  • Supabase Storage Image Persistence & EXIF GPS Extraction: Upload compressed specimen JPEGs to a public Supabase Storage bucket and parse embedded EXIF GPS coordinates from uploaded camera-roll photos automatically.
  • iNaturalist & GBIF Taxonomic Cross-Validation: Cross-check Gemini Vision's species_scientific prediction against nearby iNaturalist research-grade observations within a 25 km radius to calibrate taxonomic confidence.
  • Offline PWA Queue with Background Sync: Cache field observations in IndexedDB when hikers are out of cell range in the Cascades or Coast Range, syncing automatically when connectivity returns.