Documentation / MapLibre maps and globes
MapLibre maps and globes
Use the same Mapsource tiles in a flat map or on an interactive Earth. MapLibre GL JS reprojects the tiles in the browser; you do not need a separate globe tileset.
On this page
Try the map and globe
The Mapsource theme and 3D terrain are enabled by default. Drag to turn the Earth, zoom into streets, and choose Explore terrain to inspect the Alps. Globe projection becomes a local Mercator view as you zoom in. Try the same control in the full map app.
MapLibre GL JS 5 and later support globe projection with vector and raster sources. Terrain is a separate elevation layer. This example displays Mapsource’s cartographic basemap; satellite photography and photorealistic buildings require their own licensed sources. Web Mercator tiles cover approximately 85° south to 85° north; they do not supply polar imagery. See MapLibre’s globe example.
Start with a compiled vector style
Install maplibre-gl and import its CSS. Give the map container a height. The compiled style supplies the vector source, layers, fonts and attribution, so you can use the same styling on a globe or a flat map.
This example runs in a private tool where the user supplies their own key. For a public app, keep your subscription key on the server and use an authenticated proxy with an explicit endpoint allowlist and request limits, as the Mapsource app does. Never ship a shared subscription key in JavaScript.
npm install maplibre-glimport maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";
import { installMapsourceUI } from "https://mapsource.io/map-ui/v1/map-ui.mjs";
// Also load https://mapsource.io/map-ui/v1/map-ui.css after MapLibre's CSS.
const api = "https://api.mapsource.io";
const apiKey = window.prompt("Your Mapsource API key");
if (!apiKey) throw new Error("An API key is required");
const response = await fetch(api + "/styles/mapsource/style.json");
if (!response.ok) throw new Error("The basemap style could not load");
const style = await response.json();
const map = new maplibregl.Map({
container: "map", // e.g. <div id="map" style="height:600px"></div>
center: [-20, 20], zoom: 1.2,
style: { ...style, projection: { type: "globe" } },
attributionControl: { compact: true },
transformRequest(url) {
const target = new URL(url, api);
const path = target.pathname.replace(/^\/api(?=\/)/, "");
const authenticated = target.origin === api &&
/^\/(tiles|glyphs|terrain)\//.test(path);
return authenticated
? { url, headers: { Authorization: "Bearer " + apiKey } }
: { url };
}
});
map.addControl(new maplibregl.NavigationControl());
const disposeUI = installMapsourceUI(map);
// On teardown: disposeUI(); map.remove();Retain the Mapsource helper’s attribution control and the source attribution. If your bundler separates MapLibre workers, configure its worker URL to a copy from the installed MapLibre version. See themed controls and labels and the style compiler.
Switch between a 2D map and a 3D globe
Call setProjection after the style has loaded. A projection switch retains the map instance, sources, results and event handlers. Zoom out to see the Earth’s curvature; changing pitch alone only tilts the camera.
let view = "globe";
function selectView(next) {
view = next;
map.setProjection({ type: view });
map.easeTo({
pitch: 0, bearing: 0,
...(view === "globe" ? { zoom: Math.min(map.getZoom(), 1.5) } : {}),
duration: matchMedia("(prefers-reduced-motion: reduce)").matches ? 0 : 900
});
}
// Wire to your buttons once map's load event has fired:
// selectView("mercator"); // 2D
// selectView("globe"); // 3D Earth
map.on("style.load", () => map.setProjection({ type: view }));Keep the controls’ aria-pressed state in sync with the selected mode. Reapply the mode on style.load: a new style can otherwise restore its own projection.
Wrap raster tiles onto the Earth
For a pre-rendered basemap, use this style in the map constructor above. The same authentication hook and projection buttons apply. Raster tiles contain rendered pixels; vector tiles support client styling and feature queries.
const style = {
version: 8,
projection: { type: "globe" },
sources: {
basemap: {
type: "raster", tileSize: 256, maxzoom: 20,
tiles: [api + "/tiles/dark/{z}/{x}/{y}.png"],
attribution: "© OpenMapTiles · © OpenStreetMap contributors · CARTO"
}
},
layers: [{ id: "basemap", type: "raster", source: "basemap" }]
};Use light in place of dark for Positron. Read current templates, zoom ranges and attribution from the tile catalog.
Add geographic results to either view
MapLibre draws GeoJSON overlays in both projections. These sample coordinates describe a line between two places; use returned route geometry to display an actual route. Overpass JSON needs conversion to GeoJSON first.
function restoreResults() {
if (!map.getSource("results")) map.addSource("results", {
type: "geojson",
data: { type: "Feature", properties: {}, geometry: {
type: "LineString", coordinates: [[2.35, 48.86], [139.69, 35.68]]
} }
});
if (!map.getLayer("results-line")) map.addLayer({
id: "results-line", type: "line", source: "results",
paint: { "line-color": "#d9ff72", "line-width": 3 }
});
}
map.on("style.load", restoreResults);
// If the style is already loaded, call restoreResults() now.For place names, categories, selected labels and keyboard-accessible results, use the place-label helper.
Plot weather and environmental data
The weather explorer lets you choose a product, native file, field, time and level, then adjust colors and opacity in either map projection. Scalar grids use value-colored geographic cells. Satellite detections use their actual point locations; NWS forecasts stay at their requested location, and alerts retain their published geometry.
Discover a real source file, inspect its fields and pin its ETag before submitting a visualization job. Large products decode in the background. Keep the returned job ID and poll its status; reconnecting to that job does not require submitting another one. Submission uses one quota unit, including failed jobs. Status and result reads do not use quota units; weather transfer limits still apply.
// Uses api, apiKey and the loaded map from the vector example above.
const auth = { Authorization: "Bearer " + apiKey };
async function json(url, options = {}) {
const response = await fetch(url, options);
const body = await response.json();
if (!response.ok) throw new Error(body.error?.message || "Weather request failed");
return body;
}
const sourceId = "noaa-gfs";
const source = api + "/weather/sources/" + sourceId;
const date = new Date().toISOString().slice(0, 10).replaceAll("-", "");
const files = await json(source + "/visualization-assets?date=" + date, { headers: auth });
const objectKey = files.selectedKey ?? files.assets[0]?.key;
if (!objectKey) throw new Error("No source file for this date; choose another date");
const fields = await json(source + "/visualization-fields?" +
new URLSearchParams({ objectKey }), { headers: auth });
const field = fields.fields.find(item => item.id === fields.defaultFieldId);
if (!field) throw new Error("No native field was discovered");
const idempotencyKey = crypto.randomUUID();
// Save this key and exact input before the first POST; reuse both after a connection loss.
let job = await json(source + "/visualizations", {
method: "POST",
headers: { ...auth, "Content-Type": "application/json", "If-Match": fields.etag,
"Idempotency-Key": idempotencyKey },
body: JSON.stringify({ objectKey, field: field.id,
level: field.levels[0]?.index ?? 0, time: field.times[0]?.index ?? 0,
maxPoints: 4096 })
});
const jobUrl = api + "/weather/visualizations/" + encodeURIComponent(job.id);
const deadline = Math.min(Date.now() + 600000, Date.parse(job.expiresAt));
while (job.state === "queued" || job.state === "running") {
if (Date.now() >= deadline) throw new Error("Visualization job expired");
await new Promise(resolve => setTimeout(resolve, Math.max(3000, job.retryAfterMs)));
job = await json(jobUrl, { headers: auth });
}
if (job.state !== "ready") throw new Error(job.error?.message || "Source decoding failed");
const result = await json(jobUrl + "/result", { headers: auth });
if (result.source.etag !== fields.etag) throw new Error("Source version changed");
const values = result.features.map(feature => feature.properties.value);
const low = values.length ? Math.min(...values) : 0;
const high = values.length ? Math.max(...values) : 1;
const colors = ["#234638", "#5e9175", "#b8d09a", "#e0cf75", "#e79160"];
const color = result.field.categorical && result.field.categories?.length
? ["match", ["get", "value"], ...result.field.categories.flatMap((category, i) =>
[category.value, colors[Math.round(i * 4 / Math.max(1, result.field.categories.length - 1))]]), "#868e83"]
: ["interpolate", ["linear"], ["get", "value"],
low === high ? low - 0.5 : low, colors[0],
low === high ? high + 0.5 : high, colors[4]];
const polygons = ["scalar-grid", "alert-geometry"].includes(result.renderKind);
function restoreWeather() {
if (!map.getSource("weather")) map.addSource("weather", {
type: "geojson", data: result, attribution: result.source.attribution
});
if (!map.getLayer("weather-values")) map.addLayer({
id: "weather-values", source: "weather", type: polygons ? "fill" : "circle",
paint: polygons
? { "fill-color": color, "fill-opacity": 0.75 }
: { "circle-color": color, "circle-opacity": 0.75, "circle-radius": 3 }
});
}
map.on("style.load", restoreWeather);
if (map.isStyleLoaded()) restoreWeather();
const legend = document.createElement("p");
legend.textContent = result.features.length
? result.field.label + " · " + result.field.units + " · sample range " + low + "–" + high
: "No plottable source values in this selection";
map.getContainer().after(legend);
console.log({ source: result.source, times: result.times,
sampling: result.sample, transformations: result.transformations });
// On teardown: map.off("style.load", restoreWeather); legend.remove();The response’s renderKind distinguishes scalar cells, point observations, location forecasts and alert geometry. Keep units, source time, missing counts, sampling, transformations and attribution beside the map. The range above describes returned samples, not a claim about the entire native model. A valid empty result stays empty; do not draw replacement cells or alert locations.
For point observations only, a MapLibre heatmap can show smoothed, value-weighted density. Its colors represent relative concentration, not the source field’s physical units. Keep direct value-colored points available and label the density view explicitly. Do not interpolate categorical reef or alert levels into new categories.
if (result.renderKind === "point-observations" && !result.field.categorical) {
map.addLayer({
id: "weather-density", source: "weather", type: "heatmap",
paint: {
"heatmap-weight": ["max", 0, ["min", 1,
["/", ["-", ["get", "value"], low], Math.max(high - low, 1e-12)]]],
"heatmap-color": ["interpolate", ["linear"], ["heatmap-density"],
0, "rgba(0,0,0,0)", 0.2, colors[0], 1, colors[4]],
"heatmap-radius": 18, "heatmap-intensity": 1, "heatmap-opacity": 0.75
}
});
// Connect these to your sliders; radius is in screen pixels.
map.setPaintProperty("weather-density", "heatmap-radius", 24);
map.setPaintProperty("weather-density", "heatmap-intensity", 1.2);
map.setPaintProperty("weather-density", "heatmap-opacity", 0.6);
}
// For scalar cells, change weather-values fill-color/fill-opacity instead.
// Restore your selected layers and paint settings after each style.load.Use the public product catalog to discover eligible products and their delivery capabilities. The weather API guide covers native downloads, source rights and transfer limits. The viewer’s display transforms do not replace the original source data.
Add terrain relief when exploring locally
Globe projection controls the shape of the Earth. A raster DEM adds ground elevation independently. The Mapsource terrain endpoint uses Terrarium encoding; use the exact encoding below.
function restoreTerrain() {
if (!map.getSource("terrain")) map.addSource("terrain", {
type: "raster-dem", tileSize: 256, maxzoom: 15,
tiles: [api + "/terrain/{z}/{x}/{y}.png"],
encoding: "terrarium",
attribution: "Mapzen Terrain Tiles · AWS Open Data"
});
map.setTerrain({ source: "terrain", exaggeration: 1.4 });
}
map.on("style.load", restoreTerrain);
// After the map has loaded, fly to a mountain region:
// map.flyTo({ center: [6.87, 45.83], zoom: 11, pitch: 60 });Elevation requests count toward usage. The live example enables relief in 3D mode at a subtle 1.2× exaggeration and turns it off in 2D mode. Hillshade appears as you zoom into regional terrain. See terrain and elevation.
Preserve projection and overlays across style changes
setStyle replaces style-owned state. Keep your selected projection and returned results in application state, then restore projection, sources, layers and optional terrain in style.load, as above. Switching projection alone does not require setStyle. Avoid recreating the map or resetting its camera when changing a basemap.
In React, create the map once in an effect, use refs for current selections in map callbacks, and clean up listeners, controls and the map on unmount. The Mapsource app source includes the complete React integration.
Questions about this guide? .