Skip to content

Display cloud cover with MapLibre GL JS

Add the latest cloud layer to NASA Blue Marble satellite imagery with MapLibre GL JS, centered on the southeast Pacific. The basemap is a static, cloud-free composite; clouds come from a separate Rainbow API layer.

Weather Map Tiles API

Keep your API key on the server

We do not recommend putting API keys in frontend code. Browser code and network requests are visible to users. This example calls a backend proxy on the same origin; only the server adds the API key.

Cloud cover over the southeast Pacific on NASA Blue Marble imagery in MapLibre

Static preview. The weather will differ when you run the example.

Basemap imagery provided by NASA GIBS, part of NASA ESDIS.

Map example

Save as clouds.html. It uses MapLibre GL JS 6.18.0 and requests a snapshot for the clouds layer. Cloud tile URLs contain the snapshot and XYZ coordinates, without a forecast-offset segment or precipitation palette parameter.

Cloud tiles support native zoom levels 0–7. MapLibre enlarges the available tiles at higher zoom levels rather than requesting unsupported ones.

clouds.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Cloud cover map with MapLibre</title>
  <link
    rel="stylesheet"
    href="https://unpkg.com/[email protected]/dist/maplibre-gl.css"
  >

  <style>
    body {
      margin: 0;
      background: #071b2b;
    }

    #map {
      height: 100vh;
    }

    #error {
      position: absolute;
      top: 10px;
      left: 10px;
      padding: 12px;
      background: white;
      color: #a00;
      font: 14px sans-serif;
    }

    #error:empty {
      display: none;
    }
  </style>
</head>
<body>
  <div id="map" aria-label="Cloud cover map"></div>
  <p id="error" role="alert"></p>

  <script type="module">
    import * as maplibregl from 'https://unpkg.com/[email protected]/dist/maplibre-gl.mjs';

    // Create the map with NASA's cloud-free Blue Marble imagery.
    const map = new maplibregl.Map({
      container: 'map',
      style: {
        version: 8,
        sources: {
          satellite: {
            type: 'raster',
            tiles: [
              'https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/BlueMarble_NextGeneration/default/GoogleMapsCompatible_Level8/{z}/{y}/{x}.jpeg'
            ],
            tileSize: 256,
            maxzoom: 8,
            attribution: 'Imagery: <a href="https://earthdata.nasa.gov/gibs">NASA GIBS</a> (ESDIS) · Blue Marble'
          }
        },
        layers: [{ id: 'satellite', type: 'raster', source: 'satellite' }]
      },
      center: [-86, -25],
      zoom: 4.7
    });

    // Show map and tile loading errors.
    map.on('error', () => {
      document.getElementById('error').textContent =
        'Map data unavailable. Check the proxy and reload.';
    });

    map.on('style.load', async () => {
      // We do not recommend storing API keys in frontend code.
      // The backend proxy adds the key on the server.
      try {
        // Request the current snapshot through the backend.
        const response = await fetch('/tiles/v1/snapshot?layer=clouds');

        if (!response.ok) {
          throw new Error('Could not load weather. Check the proxy and API key.');
        }

        const { snapshot } = await response.json();

        // Add cloud cover tiles for this snapshot.
        map.addSource('weather', {
          type: 'raster',
          tiles: [`${location.origin}/tiles/v1/clouds/${snapshot}/{z}/{x}/{y}`],
          tileSize: 256,
          maxzoom: 7,
          attribution: 'Weather &copy; <a href="https://rainbow.ai/">Rainbow Weather</a>'
        });

        map.addLayer({
          id: 'weather',
          type: 'raster',
          source: 'weather',
          paint: { 'raster-opacity': 1 }
        });
      } catch (error) {
        // Show snapshot request errors on the map.
        document.getElementById('error').textContent = error.message;
      }
    });
  </script>
</body>
</html>

Backend proxy

Save the shared server below as tiles_service.py beside the HTML file. It serves the page and forwards snapshot and tile requests with the API key added on the server.

Show the Python server
tiles_service.py
"""Serve the map examples locally; the Rainbow API key never goes to the browser."""

import os
from pathlib import Path

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse, Response
import requests
import uvicorn


# Load the API key on the server. Never send it to the browser.
load_dotenv()  # Reads .env beside this file or in a parent folder.
API_KEY = os.getenv("RAINBOW_API_KEY")
API_URL = "https://api.rainbow.ai/tiles/v1"
EXAMPLE_DIR = Path(__file__).resolve().parent

app = FastAPI()


# Make authenticated requests to the Rainbow API.
def api_get(path, params):
    if not API_KEY:
        raise HTTPException(503, "Set RAINBOW_API_KEY in .env and restart the server.")

    try:
        response = requests.get(
            f"{API_URL}/{path}",
            params=params,
            headers={"Ocp-Apim-Subscription-Key": API_KEY},
            timeout=10,
            allow_redirects=False,
        )
    except requests.Timeout:
        raise HTTPException(504, "The weather API timed out. Please try again.") from None
    except requests.RequestException:
        raise HTTPException(502, "The weather API could not be reached.") from None

    if response.status_code != 200:
        status = response.status_code if 400 <= response.status_code <= 599 else 502
        raise HTTPException(
            status,
            f"Weather API returned HTTP {status}. "
            "Check your key, subscription, or requested data.",
        )

    return response


# Return the latest snapshot timestamp for the selected weather layer.
@app.get("/tiles/v1/snapshot")
def snapshot(layer: str = "precip-global"):
    if layer not in ("precip-global", "radars", "clouds"):
        raise HTTPException(422, "Choose precip-global, radars, or clouds.")

    try:
        timestamp = api_get("snapshot", {"layer": layer}).json()["snapshot"]
    except (ValueError, KeyError, TypeError):
        raise HTTPException(502, "The weather API returned an invalid snapshot.") from None

    if type(timestamp) is not int or timestamp <= 0 or timestamp % 600:
        raise HTTPException(502, "The weather API returned an invalid snapshot.")

    return JSONResponse({"snapshot": timestamp}, headers={"Cache-Control": "no-store"})


# Validate tile coordinates and upstream image responses.
def validate_tile(snapshot, zoom, x, y, max_zoom):
    if not (
        snapshot > 0
        and snapshot % 600 == 0
        and 0 <= zoom <= max_zoom
        and 0 <= x < 2**zoom
        and 0 <= y < 2**zoom
    ):
        raise HTTPException(422, "Invalid snapshot, tile coordinates, or zoom.")


def image_tile(path, params):
    response = api_get(path, params)
    content = response.content

    if content.startswith(b"\x89PNG\r\n\x1a\n"):
        media_type = "image/png"
    elif content.startswith(b"RIFF") and content[8:12] == b"WEBP":
        media_type = "image/webp"
    else:
        raise HTTPException(502, "The weather API returned an invalid tile image.")

    declared_type = response.headers.get("Content-Type", "").split(";")[0].strip().lower()
    if declared_type and declared_type != media_type:
        raise HTTPException(502, "The weather API returned a mismatched tile format.")

    return Response(content, media_type=media_type)


# Forward precipitation, radar, and cloud tiles to the browser.
@app.get("/tiles/v1/precip-global/{snapshot}/0/{zoom}/{x}/{y}")
def tile(snapshot: int, zoom: int, x: int, y: int, color: int = 0):
    validate_tile(snapshot, zoom, x, y, max_zoom=12)
    if not 0 <= color <= 9:
        raise HTTPException(422, "Choose a palette from 0 to 9.")

    return image_tile(f"precip-global/{snapshot}/0/{zoom}/{x}/{y}", {"color": color})


@app.get("/tiles/v1/radars/{snapshot}/{zoom}/{x}/{y}")
def radar_tile(
    snapshot: int,
    zoom: int,
    x: int,
    y: int,
    color: int = 0,
    use_precip_type: bool = False,
    coverage: bool = False,
):
    validate_tile(snapshot, zoom, x, y, max_zoom=7)
    if not 0 <= color <= 9:
        raise HTTPException(422, "Choose a palette from 0 to 9.")

    return image_tile(
        f"radars/{snapshot}/{zoom}/{x}/{y}",
        {
            "color": color,
            "use_precip_type": int(use_precip_type),
            "coverage": int(coverage),
        },
    )


@app.get("/tiles/v1/clouds/{snapshot}/{zoom}/{x}/{y}")
def clouds_tile(snapshot: int, zoom: int, x: int, y: int):
    validate_tile(snapshot, zoom, x, y, max_zoom=7)

    return image_tile(f"clouds/{snapshot}/{zoom}/{x}/{y}", {})


# Serve only the example HTML pages, never the key or Python source.
@app.get("/{page:path}")
def example_page(page: str):
    pages = {
        "": "leaflet.html",
        "leaflet.html": "leaflet.html",
        "maplibre": "maplibre.html",
        "maplibre.html": "maplibre.html",
        "radar": "radar.html",
        "radar.html": "radar.html",
        "clouds": "clouds.html",
        "clouds.html": "clouds.html",
    }

    filename = pages.get(page)
    if filename is None:
        raise HTTPException(404, "Page not found.")

    path = EXAMPLE_DIR / filename
    if not path.is_file():
        raise HTTPException(404, f"Save {filename} beside tiles_service.py.")

    return FileResponse(path)


# Start the local example server.
if __name__ == "__main__":
    uvicorn.run(app, host="127.0.0.1", port=8000)

Run locally

Use Python 3.10+. Create a folder for the two files above and install the dependencies:

Bash
python -m venv .venv
source .venv/bin/activate
python -m pip install fastapi uvicorn requests python-dotenv

On Windows, activate with .venv\Scripts\activate instead. Get a key from Getting started, then create .env beside tiles_service.py:

.env
RAINBOW_API_KEY=YOUR_API_KEY

Keep .env out of source control. Start the server from the folder containing the files:

Bash
python tiles_service.py

Open http://127.0.0.1:8000/clouds rather than opening the HTML file directly. Drag and zoom to explore; reload the page to fetch the latest snapshot. If an error appears, check the proxy, your key, and subscription access.

Each fetched weather tile uses your API allowance. See the Tiles API reference, radar example, or precipitation forecast example.