Choropleth of the world
Every country filled by its GDP per person, its value on hover, with a legend on the map.
Map and code
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
Loading the map…
The map couldn't load.
These maps come from Google Maps and OpenFreeMap, which see your IP address. They stay off until you say so, once for the whole site. What loading the maps sends
Fetches countries.jsonStyled by choropleth.css
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- The world's countries, each filled by its GDP per person (Natural Earth's figures, in
countries.json), on a globe its toggle flattens: hovering one shows its value, and a legend
on the map's bottom left holds the classes and a select of every country, for the keyboard. -->
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../../styles/choropleth.css">
<maplace-map id="choropleth-maplibre-map" globe popup-open-on="hover" center="20,10" zoom="2"
list="choropleth-maplibre-legend" list-position="bottom-left"></maplace-map>
<script>
// The legend's classes, lowest first, each with its colour: a scale colour-blind readers
// can tell apart. In a plain script, run as the page is read, so the legend's list view is
// defined before the map opens; the module below shades the countries with the same classes.
const choroplethMaplibreClasses = [
{ below: 1500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const choroplethMaplibreNoData = { fill: "#d1d5db", label: "No data" };
// The legend, a list view of your own: each class with its colour, then a select of every
// country, for the keyboard.
Maplace.defineListView("choropleth-maplibre-legend", (maplace) => {
const countries = Maplace.createListView(maplace, { as: "select", label: "Country" });
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
for (const { fill, label } of [...choroplethMaplibreClasses, choroplethMaplibreNoData]) {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
classes.append(entry);
}
legend.append(title, classes, countries.element);
return { element: legend, destroy: () => { countries.destroy(); legend.remove(); } };
});
</script>
<script type="module">
// Every country's outline, white between neighbours; under the pointer, its colour at full
// strength and a dark outline; selected, a wider one.
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const classOf = (value) =>
value === null ? choroplethMaplibreNoData : (choroplethMaplibreClasses.find(({ below }) => value < below) ?? choroplethMaplibreNoData);
// A country filled in its class's colour, its value in the popup hovering it opens.
const shaded = (country) => {
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? choroplethMaplibreNoData.label : `${dollars.format(value)} per person`;
return { ...country, style: { ...OUTLINE, fill: classOf(value).fill }, hoveredStyle: HOVERED, selectedStyle: SELECTED, content };
};
const response = await fetch("/examples/data/countries.json");
document.getElementById("choropleth-maplibre-map").locations =
Maplace.locationsFromGeoJSON(await response.json()).map(shaded);
</script><!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- The world's countries, each filled by its GDP per person (Natural Earth's figures, in
countries.json): hovering one shows its value, and a legend on the map's bottom left holds
the classes and a select of every country, for the keyboard. -->
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../styles/choropleth.css">
<maplace-map id="choropleth-map" api-key="YOUR_KEY" popup-open-on="hover" center="20,10" zoom="2"
list="choropleth-legend" list-position="bottom-left"></maplace-map>
<script>
// The legend's classes, lowest first, each with its colour: a scale colour-blind readers
// can tell apart. In a plain script, run as the page is read, so the legend's list view is
// defined before the map opens; the module below shades the countries with the same classes.
const choroplethClasses = [
{ below: 1500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const choroplethNoData = { fill: "#d1d5db", label: "No data" };
// The legend, a list view of your own: each class with its colour, then a select of every
// country, for the keyboard.
Maplace.defineListView("choropleth-legend", (maplace) => {
const countries = Maplace.createListView(maplace, { as: "select", label: "Country" });
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
for (const { fill, label } of [...choroplethClasses, choroplethNoData]) {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
classes.append(entry);
}
legend.append(title, classes, countries.element);
return { element: legend, destroy: () => { countries.destroy(); legend.remove(); } };
});
</script>
<script type="module">
// Every country's outline, white between neighbours; under the pointer, its colour at full
// strength and a dark outline; selected, a wider one.
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const classOf = (value) =>
value === null ? choroplethNoData : (choroplethClasses.find(({ below }) => value < below) ?? choroplethNoData);
// A country filled in its class's colour, its value in the popup hovering it opens.
const shaded = (country) => {
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? choroplethNoData.label : `${dollars.format(value)} per person`;
return { ...country, style: { ...OUTLINE, fill: classOf(value).fill }, hoveredStyle: HOVERED, selectedStyle: SELECTED, content };
};
const response = await fetch("/examples/data/countries.json");
document.getElementById("choropleth-map").locations =
Maplace.locationsFromGeoJSON(await response.json()).map(shaded);
</script><!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, what the map mounts on, and the map made with Maplace, on a globe its toggle flattens; the countries come from countries.json, Natural Earth's, each filled by its GDP per person, its value in a popup on hover, and a legend with the countries' select on the map. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../../styles/choropleth.css">
<style>
#choropleth-maplibre-script-map { height: 24rem; }
</style>
<div id="choropleth-maplibre-script-map"></div>
<script type="module">
// The legend's classes, lowest first, each with its colour: a scale colour-blind readers
// can tell apart.
const CLASSES = [
{ below: 1500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
// Every country's outline, white between neighbours; under the pointer, its colour at full
// strength and a dark outline; selected, a wider one.
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const maplace = Maplace.createMaplace({
popup: { openOn: "hover" },
// The world from Europe and Africa, where the globe opens too, rather than fitted round it.
view: { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 },
});
// The earth as a globe, with a toggle on the map to flatten it.
const adapter = Maplace.createMapLibreAdapter({ globe: true });
maplace.attach(adapter, "#choropleth-maplibre-script-map");
const countries = Maplace.createListView(maplace, { as: "select", label: "Country" });
adapter.mountControl(legendWith(countries.element), "bottom-left");
const response = await fetch("/examples/data/countries.json");
maplace.setLocations(Maplace.locationsFromGeoJSON(await response.json()).map(shaded));
// A country filled in its class's colour, its value in the popup hovering it opens.
function shaded(country) {
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return { ...country, style: { ...OUTLINE, fill: classOf(value).fill }, hoveredStyle: HOVERED, selectedStyle: SELECTED, content };
}
function classOf(value) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
// The legend: each class with its colour, then the countries' select, for the keyboard.
function legendWith(select) {
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
classes.append(...[...CLASSES, NO_DATA].map(legendEntry));
legend.append(title, classes, select);
return legend;
}
function legendEntry({ fill, label }) {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
return entry;
}
</script><!doctype html>
<!-- A page of your own script: the CDN script, what the map mounts on, and the map made with Maplace, which adds Maps JS with your key; the countries come from countries.json, Natural Earth's, each filled by its GDP per person, its value in a popup on hover, and a legend with the countries' select on the map. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../styles/choropleth.css">
<style>
#choropleth-script-map { height: 24rem; }
</style>
<div id="choropleth-script-map"></div>
<script type="module">
// The legend's classes, lowest first, each with its colour: a scale colour-blind readers
// can tell apart.
const CLASSES = [
{ below: 1500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
// Every country's outline, white between neighbours; under the pointer, its colour at full
// strength and a dark outline; selected, a wider one.
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
const maplace = Maplace.createMaplace({
popup: { openOn: "hover" },
// The world from Europe and Africa, where the globe opens too, rather than fitted round it.
view: { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 },
});
const adapter = Maplace.createGoogleAdapter({ apiKey: "YOUR_KEY" });
maplace.attach(adapter, "#choropleth-script-map");
const countries = Maplace.createListView(maplace, { as: "select", label: "Country" });
adapter.mountControl(legendWith(countries.element), "bottom-left");
const response = await fetch("/examples/data/countries.json");
maplace.setLocations(Maplace.locationsFromGeoJSON(await response.json()).map(shaded));
// A country filled in its class's colour, its value in the popup hovering it opens.
function shaded(country) {
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return { ...country, style: { ...OUTLINE, fill: classOf(value).fill }, hoveredStyle: HOVERED, selectedStyle: SELECTED, content };
}
function classOf(value) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
// The legend: each class with its colour, then the countries' select, for the keyboard.
function legendWith(select) {
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
classes.append(...[...CLASSES, NO_DATA].map(legendEntry));
legend.append(title, classes, select);
return legend;
}
function legendEntry({ fill, label }) {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
return entry;
}
</script><!doctype html>
<!-- The page vanilla.ts runs on: what the module mounts on, and the module, which brings maplibre-gl and its stylesheet. -->
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../../styles/choropleth.css">
<style>
#choropleth-maplibre-vanilla-map { height: 24rem; }
</style>
<div id="choropleth-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>import "maplibre-gl/dist/maplibre-gl.css";
import {
createListView,
createMaplace,
type Location,
locationsFromGeoJSON,
} from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
/** What the file says of a country: its GDP per person in US dollars, null where it has none. */
interface Country {
readonly gdpPerPerson: number | null;
}
/**
* The legend's classes, lowest first, each with its colour: a scale colour-blind readers can tell
* apart.
*/
const CLASSES = [
{ below: 1_500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4_000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10_000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30_000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
/**
* Every country's outline, white between neighbours; under the pointer, its colour at full
* strength and a dark outline; selected, a wider one.
*/
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
const maplace = createMaplace<Country>({
popup: { openOn: "hover" },
// The world from Europe and Africa, where the globe opens too, rather than fitted round it.
view: { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 },
});
// The earth as a globe, with a toggle on the map to flatten it.
const adapter = createMapLibreAdapter({ globe: true });
maplace.attach(adapter, "#choropleth-maplibre-vanilla-map");
const countries = createListView(maplace, { as: "select", label: "Country" });
adapter.mountControl(legendWith(countries.element), "bottom-left");
const response = await fetch("/examples/data/countries.json");
maplace.setLocations(locationsFromGeoJSON<Country>(await response.json()).map(shaded));
/** A country filled in its class's colour, its value in the popup hovering it opens. */
function shaded(country: Location<Country>): Location<Country> {
if (country.type !== "polygon" && country.type !== "multipolygon") return country;
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return {
...country,
style: { ...OUTLINE, fill: classOf(value).fill },
hoveredStyle: HOVERED,
selectedStyle: SELECTED,
content,
};
}
function classOf(value: number | null) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
/** The legend: each class with its colour, then the countries' select, for the keyboard. */
function legendWith(select: HTMLElement): HTMLElement {
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
classes.append(...[...CLASSES, NO_DATA].map(legendEntry));
legend.append(title, classes, select);
return legend;
}
function legendEntry({ fill, label }: { fill: string; label: string }): HTMLLIElement {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
return entry;
}<!doctype html>
<!-- The page vanilla.ts runs on: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "YOUR_KEY",
v: "weekly",
});
</script><!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../styles/choropleth.css">
<style>
#choropleth-vanilla-map { height: 24rem; }
</style>
<div id="choropleth-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>import {
createListView,
createMaplace,
type Location,
locationsFromGeoJSON,
} from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
/** What the file says of a country: its GDP per person in US dollars, null where it has none. */
interface Country {
readonly gdpPerPerson: number | null;
}
/**
* The legend's classes, lowest first, each with its colour: a scale colour-blind readers can tell
* apart.
*/
const CLASSES = [
{ below: 1_500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4_000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10_000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30_000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
/**
* Every country's outline, white between neighbours; under the pointer, its colour at full
* strength and a dark outline; selected, a wider one.
*/
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
const dollars = new Intl.NumberFormat("en", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
const maplace = createMaplace<Country>({
popup: { openOn: "hover" },
// The world from Europe and Africa, where the globe opens too, rather than fitted round it.
view: { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 },
});
const adapter = createGoogleAdapter();
maplace.attach(adapter, "#choropleth-vanilla-map");
const countries = createListView(maplace, { as: "select", label: "Country" });
adapter.mountControl(legendWith(countries.element), "bottom-left");
const response = await fetch("/examples/data/countries.json");
maplace.setLocations(locationsFromGeoJSON<Country>(await response.json()).map(shaded));
/** A country filled in its class's colour, its value in the popup hovering it opens. */
function shaded(country: Location<Country>): Location<Country> {
if (country.type !== "polygon" && country.type !== "multipolygon") return country;
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return {
...country,
style: { ...OUTLINE, fill: classOf(value).fill },
hoveredStyle: HOVERED,
selectedStyle: SELECTED,
content,
};
}
function classOf(value: number | null) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
/** The legend: each class with its colour, then the countries' select, for the keyboard. */
function legendWith(select: HTMLElement): HTMLElement {
const legend = document.createElement("div");
legend.className = "choropleth-legend";
const title = document.createElement("p");
title.className = "choropleth-legend-title";
title.textContent = "GDP per person";
const classes = document.createElement("ul");
classes.className = "choropleth-classes";
classes.append(...[...CLASSES, NO_DATA].map(legendEntry));
legend.append(title, classes, select);
return legend;
}
function legendEntry({ fill, label }: { fill: string; label: string }): HTMLLIElement {
const entry = document.createElement("li");
const swatch = document.createElement("span");
swatch.className = "choropleth-swatch";
swatch.style.background = fill;
entry.append(swatch, label);
return entry;
}<!doctype html>
<!-- The page react.tsx renders into: what the module mounts on, and the module, which brings maplibre-gl and its stylesheet. -->
<!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../../styles/choropleth.css">
<style>
#choropleth-maplibre-react-root .map { height: 24rem; }
</style>
<div id="choropleth-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>import "maplibre-gl/dist/maplibre-gl.css";
import { type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { LocationList, MapControl, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
/** What the file says of a country: its GDP per person in US dollars, null where it has none. */
interface Country {
readonly gdpPerPerson: number | null;
}
/**
* The legend's classes, lowest first, each with its colour: a scale colour-blind readers can tell
* apart.
*/
const CLASSES = [
{ below: 1_500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4_000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10_000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30_000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
/**
* Every country's outline, white between neighbours; under the pointer, its colour at full
* strength and a dark outline; selected, a wider one.
*/
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
/** The world from Europe and Africa, where the globe opens too, rather than fitted round it. */
const FIRST_VIEW = { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 } as const;
const dollars = new Intl.NumberFormat("en", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
/** A country filled in its class's colour, its value in the popup hovering it opens. */
function shaded(country: Location<Country>): Location<Country> {
if (country.type !== "polygon" && country.type !== "multipolygon") return country;
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return {
...country,
style: { ...OUTLINE, fill: classOf(value).fill },
hoveredStyle: HOVERED,
selectedStyle: SELECTED,
content,
};
}
function classOf(value: number | null) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
/** The legend: each class with its colour, then the countries' select, for the keyboard. */
function Legend() {
return (
<div className="choropleth-legend">
<p className="choropleth-legend-title">GDP per person</p>
<ul className="choropleth-classes">
{[...CLASSES, NO_DATA].map(({ fill, label }) => (
<li key={label}>
<span className="choropleth-swatch" style={{ background: fill }} />
{label}
</li>
))}
</ul>
<LocationList as="select" label="Country" />
</div>
);
}
// The earth as a globe, with a toggle on the map to flatten it.
const onTheGlobe = () => createMapLibreAdapter({ globe: true });
function Choropleth() {
const [countries, setCountries] = useState<readonly Location<Country>[]>([]);
useEffect(() => {
fetch("/examples/data/countries.json")
.then((response) => response.json())
.then((collection) => setCountries(locationsFromGeoJSON<Country>(collection).map(shaded)));
}, []);
return (
<MaplaceProvider locations={countries} popup={{ openOn: "hover" }} view={FIRST_VIEW}>
<MaplaceMap createAdapter={onTheGlobe} className="map">
<MapControl position="bottom-left">
<Legend />
</MapControl>
</MaplaceMap>
</MaplaceProvider>
);
}
createRoot(document.getElementById("choropleth-maplibre-react-root") as HTMLElement).render(
<StrictMode>
<Choropleth />
</StrictMode>,
);<!doctype html>
<!-- The page react.tsx renders into: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->Google's bootstrap loader, with your API key: from Google's docs
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
key: "YOUR_KEY",
v: "weekly",
});
</script><!-- This example's look lives in the examples' styles/choropleth.css, which every version links. -->
<link rel="stylesheet" href="../styles/choropleth.css">
<style>
#choropleth-react-root .map { height: 24rem; }
</style>
<div id="choropleth-react-root"></div>
<script type="module" src="./react.tsx"></script>import { type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { LocationList, MapControl, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
/** What the file says of a country: its GDP per person in US dollars, null where it has none. */
interface Country {
readonly gdpPerPerson: number | null;
}
/**
* The legend's classes, lowest first, each with its colour: a scale colour-blind readers can tell
* apart.
*/
const CLASSES = [
{ below: 1_500, fill: "#ffffcc", label: "Under $1,500" },
{ below: 4_000, fill: "#a1dab4", label: "$1,500–4,000" },
{ below: 10_000, fill: "#41b6c4", label: "$4,000–10,000" },
{ below: 30_000, fill: "#2c7fb8", label: "$10,000–30,000" },
{ below: Number.POSITIVE_INFINITY, fill: "#253494", label: "Over $30,000" },
];
const NO_DATA = { fill: "#d1d5db", label: "No data" };
/**
* Every country's outline, white between neighbours; under the pointer, its colour at full
* strength and a dark outline; selected, a wider one.
*/
const OUTLINE = { stroke: "#ffffff", strokeWidth: 1, fillOpacity: 0.75 };
const HOVERED = { stroke: "#111827", strokeWidth: 2, fillOpacity: 1 };
const SELECTED = { ...HOVERED, strokeWidth: 3 };
/** The world from Europe and Africa, where the globe opens too, rather than fitted round it. */
const FIRST_VIEW = { kind: "center", center: { lat: 20, lng: 10 }, zoom: 2 } as const;
const dollars = new Intl.NumberFormat("en", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
/** A country filled in its class's colour, its value in the popup hovering it opens. */
function shaded(country: Location<Country>): Location<Country> {
if (country.type !== "polygon" && country.type !== "multipolygon") return country;
const value = country.data?.gdpPerPerson ?? null;
const content = value === null ? NO_DATA.label : `${dollars.format(value)} per person`;
return {
...country,
style: { ...OUTLINE, fill: classOf(value).fill },
hoveredStyle: HOVERED,
selectedStyle: SELECTED,
content,
};
}
function classOf(value: number | null) {
return value === null ? NO_DATA : (CLASSES.find(({ below }) => value < below) ?? NO_DATA);
}
/** The legend: each class with its colour, then the countries' select, for the keyboard. */
function Legend() {
return (
<div className="choropleth-legend">
<p className="choropleth-legend-title">GDP per person</p>
<ul className="choropleth-classes">
{[...CLASSES, NO_DATA].map(({ fill, label }) => (
<li key={label}>
<span className="choropleth-swatch" style={{ background: fill }} />
{label}
</li>
))}
</ul>
<LocationList as="select" label="Country" />
</div>
);
}
function Choropleth() {
const [countries, setCountries] = useState<readonly Location<Country>[]>([]);
useEffect(() => {
fetch("/examples/data/countries.json")
.then((response) => response.json())
.then((collection) => setCountries(locationsFromGeoJSON<Country>(collection).map(shaded)));
}, []);
return (
<MaplaceProvider locations={countries} popup={{ openOn: "hover" }} view={FIRST_VIEW}>
<MaplaceMap createAdapter={createGoogleAdapter} className="map">
<MapControl position="bottom-left">
<Legend />
</MapControl>
</MaplaceMap>
</MaplaceProvider>
);
}
createRoot(document.getElementById("choropleth-react-root") as HTMLElement).render(
<StrictMode>
<Choropleth />
</StrictMode>,
);How it works
The world’s countries, each filled by its GDP per person: a country of several polygons, as the United States with Alaska and Hawaii, is one multipolygon location, hovered, selected and listed as one.
- The data:
countries.json, Natural Earth’s 1:110m countries, which are public domain, as GeoJSON, each with its GDP per person (its GDP over its population, for years from 2007 to 2019, mostly 2019; none under 10,000 people). Its borders are Natural Earth’s, as they stand on the ground; Antarctica is left out. - HTML:
popup-open-on="hover"on<maplace-map>, which opens a country’s popup under the pointer (Map attributes), and a list view of your own, holding the legend and a select of the countries, placed in a corner withlist-position(List views), defined in a plain script so it exists before the map opens; a module script then fetches the countries and assignslocations, shading each one first, which a file named bysrccouldn’t do. - Script and Bundler:
locationsFromGeoJSON, each country’sstyle,hoveredStyleandselectedStyleset from its value (Styles),popup: { openOn: "hover" }(Popup options), andmountControlwith acreateListViewselect inside the legend. - React: the same locations on
<MaplaceProvider popup>, and a<MapControl>holding the legend and<LocationList as="select">(<MapControl>). - On MapLibre, a globe:
globeon the map opens it as the earth, with a “Globe” toggle that flattens it (Globe). Google’s map has no globe.