# Choropleth of the world

Every country filled by its GDP per person, its value on hover, with a legend on the map.

## 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](/element/#map-attributes)), and a list view of your own, holding the legend and a select of the countries, placed in a corner with `list-position` ([List views](/element/#list-views)), defined in a plain script so it exists before the map opens; a module script then fetches the countries and assigns `locations`, shading each one first, which a file named by `src` couldn't do.
- **Script** and **Bundler**: [`locationsFromGeoJSON`](/locations/#from-geojson), each country's `style`, `hoveredStyle` and `selectedStyle` set from its value ([Styles](/locations/#styles)), `popup: { openOn: "hover" }` ([Popup options](/store/#popup-options)), and `mountControl` with a [`createListView`](/store/#list-view-options) select inside the legend.
- **React**: the same locations on `<MaplaceProvider popup>`, and a `<MapControl>` holding the legend and `<LocationList as="select">` ([`<MapControl>`](/react/#mapcontrol)).
- **On MapLibre, a globe**: `globe` on the map opens it as the earth, with a "Globe" toggle that flattens it ([Globe](/maplibre/#globe)). Google's map has no globe.

## Code

### HTML on MapLibre

`packages/maplace/examples/choropleth/maplibre/page.html`

```html
<!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>
```

### HTML on Google

`packages/maplace/examples/choropleth/page.html`

```html
<!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>
```

### Script on MapLibre

`packages/maplace/examples/choropleth/maplibre/script.html`

```html
<!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>
```

### Script on Google

`packages/maplace/examples/choropleth/script.html`

```html
<!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>
```

### Bundler on MapLibre

`packages/maplace/examples/choropleth/maplibre/vanilla.html`

```html
<!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>
```

`packages/maplace/examples/choropleth/maplibre/vanilla.ts`

```ts
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;
}
```

### Bundler on Google

`packages/maplace/examples/choropleth/vanilla.html`

```html
<!doctype html>
<!-- The page vanilla.ts runs on: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->
<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>
```

`packages/maplace/examples/choropleth/vanilla.ts`

```ts
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;
}
```

### React on MapLibre

`packages/maplace/examples/choropleth/maplibre/react.html`

```html
<!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>
```

`packages/maplace/examples/choropleth/maplibre/react.tsx`

```tsx
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>,
);
```

### React on Google

`packages/maplace/examples/choropleth/react.html`

```html
<!doctype html>
<!-- The page react.tsx renders into: Maps JS from Google's bootstrap loader, what the module mounts on, the module. -->
<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>
```

`packages/maplace/examples/choropleth/react.tsx`

```tsx
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>,
);
```

### The stylesheet every version links

`packages/maplace/examples/styles/choropleth.css`

```css
/* The choropleth example's legend, which every version links: page, script, vanilla and React, on
   either map. It sits in Maplace.js's panel on the map, which gives it a background and padding. */
.choropleth-legend {
  display: grid;
  gap: 0.375rem;
  min-width: 11rem;
}

.choropleth-legend-title {
  margin: 0;
  font-weight: 600;
}

.choropleth-classes {
  display: grid;
  gap: 0.125rem;
  margin: 0;
  padding: 0;
  list-style: none;
}

.choropleth-classes li {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* Each class's colour, set from the same table the map's fills come from, at the map's opacity. */
.choropleth-swatch {
  opacity: 0.75;
  width: 0.875rem;
  height: 0.875rem;
  border-radius: 0.125rem;
  box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.15);
}

.choropleth-legend select {
  max-width: 11rem;
}

/* On a phone, a smaller legend, so it leaves most of the map in view. */
@media (max-width: 40rem) {
  .choropleth-legend {
    gap: 0.25rem;
    min-width: 0;
    font-size: 0.6875rem;
  }

  .choropleth-swatch {
    width: 0.625rem;
    height: 0.625rem;
  }

  .choropleth-legend select {
    max-width: 8rem;
    font-size: 0.75rem;
  }
}
```
