# Share by country

Six countries in their own colours, a badge with each one's share, the list as legend.

## How it works

Six countries from `countries.json`, each in its own colour with its share in a badge, and the list beside the map as the legend: each country's name by a swatch of its colour, its share, and a row of ten dots with the share filled in, after an "All countries" entry that shows them all again. The shares are made up, for the example.

- **HTML**: the page's script turns the file into locations with `Maplace.locationsFromGeoJSON`, keeps the six, and sets the map's `locations` property; the legend is a list view of the page's own (`Maplace.defineListView` around `Maplace.createListView` with `render`) ([List views](/element/#list-views)).
- **Script** and **Bundler**: [`locationsFromGeoJSON`](/locations/#from-geojson), each country given its `style` ([Styles](/locations/#styles)), each badge a marker with an `icon` and `listed: false`, so the list holds the countries alone ([Every location](/locations/#every-location)), and `fitAll` with `fitAllLabel` for the first entry ([List view options](/store/#list-view-options)).
- **React**: `markerIcon` on `<MaplaceMap>` draws the badges, and the legend's entry is `<LocationList>`'s children ([`<LocationList>`](/react/#locationlist)).
- **Note**: a click on a badge selects it, so a `selectionChange` listener selects its country instead, as a click on its entry does, and the country's `selectedStyle` outline shows it; in React the selection is held in state.

## Code

### HTML on MapLibre

`packages/maplace/examples/share-by-country/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- Six countries, each in its own colour with its share in a badge, and the list beside the
     map as the legend: each country's name by a swatch of its colour, its share, and a row of ten
     dots with the share filled in, after an entry that shows them all; a click on a badge picks
     its country. -->
<!-- This example's look lives in the examples' styles/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../../styles/share-by-country.css">
<style>
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-maplibre-map { height: 36rem; }
    #share-by-country-maplibre-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<maplace-map id="share-by-country-maplibre-map" list="maplibre-share-by-country-legend" list-heading="Share by country" fit-all fit-all-label="All countries"></maplace-map>
<script>
  // The legend's entries, the page's own: a view defined as the page is read, so the map finds
  // it when it opens; the module below gives the map its countries.
  {
    const span = (className, ...children) => {
      const element = document.createElement("span");
      element.className = className;
      element.append(...children);
      return element;
    };
    // A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in.
    const shareEntry = ({ location }) => {
      const { share, colour } = location.data;
      const dots = span("share-dots");
      dots.setAttribute("aria-hidden", "true");
      for (let tenth = 0; tenth < 10; tenth++) {
        const dot = span("share-dot");
        dot.toggleAttribute("data-filled", tenth < share / 10);
        dots.append(dot);
      }
      const entry = span("share-entry", span("share-head", span("share-name", location.title), span("share-figure", `${share}%`)), dots);
      entry.style.setProperty("--colour", colour);
      return entry;
    };
    Maplace.defineListView("maplibre-share-by-country-legend", (maplace, { options }) =>
      Maplace.createListView(maplace, { ...options, render: shareEntry }));
  }
</script>
<script type="module">
  const span = (className, ...children) => {
    const element = document.createElement("span");
    element.className = className;
    element.append(...children);
    return element;
  };
  // A country's share on the map: the figure in a ring of its colour.
  const badgeIcon = ({ data }) => {
    const badge = span("share-badge", `${data.share}%`);
    badge.style.setProperty("--colour", data.colour);
    return badge;
  };
  // Each country's share, the colour it is drawn in, and where its badge sits. The shares are
  // made up, for the example.
  const shares = [
    { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
    { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
    { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
    { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
    { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
    { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
  ];
  const countries = Maplace.locationsFromGeoJSON(await fetch("/examples/data/countries.json").then((response) => response.json()));

  // Each country in its colour, then its badge: in the shares' order, so the list is too.
  const locations = shares.flatMap(({ id, share, colour, badge }) => {
    const country = countries.find((location) => location.id === id);
    if (country === undefined) throw new Error(`countries.json has no ${id} to shade`);
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data, icon: badgeIcon },
    ];
  });

  const map = document.getElementById("share-by-country-maplibre-map");
  map.locations = locations;
  const { maplace } = map;
  maplace.fitAll({ padding: 48 });

  // A click on a badge selects its country, as a click on its entry does.
  maplace.on("selectionChange", ({ id }) => {
    if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
  });
</script>
```

### HTML on Google

`packages/maplace/examples/share-by-country/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- Six countries, each in its own colour with its share in a badge, and the list beside the
     map as the legend: each country's name by a swatch of its colour, its share, and a row of ten
     dots with the share filled in, after an entry that shows them all; a click on a badge picks
     its country. -->
<!-- This example's look lives in the examples' styles/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../styles/share-by-country.css">
<style>
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-map { height: 36rem; }
    #share-by-country-map > .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<maplace-map id="share-by-country-map" api-key="YOUR_KEY" list="share-by-country-legend" list-heading="Share by country" fit-all fit-all-label="All countries"></maplace-map>
<script>
  // The legend's entries, the page's own: a view defined as the page is read, so the map finds
  // it when it opens; the module below gives the map its countries.
  {
    const span = (className, ...children) => {
      const element = document.createElement("span");
      element.className = className;
      element.append(...children);
      return element;
    };
    // A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in.
    const shareEntry = ({ location }) => {
      const { share, colour } = location.data;
      const dots = span("share-dots");
      dots.setAttribute("aria-hidden", "true");
      for (let tenth = 0; tenth < 10; tenth++) {
        const dot = span("share-dot");
        dot.toggleAttribute("data-filled", tenth < share / 10);
        dots.append(dot);
      }
      const entry = span("share-entry", span("share-head", span("share-name", location.title), span("share-figure", `${share}%`)), dots);
      entry.style.setProperty("--colour", colour);
      return entry;
    };
    Maplace.defineListView("share-by-country-legend", (maplace, { options }) =>
      Maplace.createListView(maplace, { ...options, render: shareEntry }));
  }
</script>
<script type="module">
  const span = (className, ...children) => {
    const element = document.createElement("span");
    element.className = className;
    element.append(...children);
    return element;
  };
  // A country's share on the map: the figure in a ring of its colour.
  const badgeIcon = ({ data }) => {
    const badge = span("share-badge", `${data.share}%`);
    badge.style.setProperty("--colour", data.colour);
    return badge;
  };
  // Each country's share, the colour it is drawn in, and where its badge sits. The shares are
  // made up, for the example.
  const shares = [
    { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
    { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
    { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
    { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
    { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
    { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
  ];
  const countries = Maplace.locationsFromGeoJSON(await fetch("/examples/data/countries.json").then((response) => response.json()));

  // Each country in its colour, then its badge: in the shares' order, so the list is too.
  const locations = shares.flatMap(({ id, share, colour, badge }) => {
    const country = countries.find((location) => location.id === id);
    if (country === undefined) throw new Error(`countries.json has no ${id} to shade`);
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data, icon: badgeIcon },
    ];
  });

  const map = document.getElementById("share-by-country-map");
  map.locations = locations;
  const { maplace } = map;
  maplace.fitAll({ padding: 48 });

  // A click on a badge selects its country, as a click on its entry does.
  maplace.on("selectionChange", ({ id }) => {
    if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
  });
</script>
```

### Script on MapLibre

`packages/maplace/examples/share-by-country/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 and its list mount on, and the map made with Maplace. -->
<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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../../styles/share-by-country.css">
<style>
  #share-by-country-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #share-by-country-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-maplibre-script-list { display: contents; }
  #share-by-country-maplibre-script-list .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-maplibre-script-map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-maplibre-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-maplibre-script-map-and-list">
  <div id="share-by-country-maplibre-script-map"></div>
  <div id="share-by-country-maplibre-script-list"></div>
</div>
<script type="module">
  const span = (className, ...children) => {
    const element = document.createElement("span");
    element.className = className;
    element.append(...children);
    return element;
  };
  // A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in.
  const shareEntry = ({ location }) => {
    const { share, colour } = location.data;
    const dots = span("share-dots");
    dots.setAttribute("aria-hidden", "true");
    for (let tenth = 0; tenth < 10; tenth++) {
      const dot = span("share-dot");
      dot.toggleAttribute("data-filled", tenth < share / 10);
      dots.append(dot);
    }
    const entry = span("share-entry", span("share-head", span("share-name", location.title), span("share-figure", `${share}%`)), dots);
    entry.style.setProperty("--colour", colour);
    return entry;
  };
  // A country's share on the map: the figure in a ring of its colour.
  const badgeIcon = ({ data }) => {
    const badge = span("share-badge", `${data.share}%`);
    badge.style.setProperty("--colour", data.colour);
    return badge;
  };

  const maplace = Maplace.createMapLibreMap("#share-by-country-maplibre-script-map", {
    view: { kind: "fit-all", padding: 48 },
    list: { container: "#share-by-country-maplibre-script-list", heading: "Share by country", fitAll: true, fitAllLabel: "All countries", render: shareEntry },
  });

  // Each country's share, the colour it is drawn in, and where its badge sits. The shares are
  // made up, for the example.
  const shares = [
    { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
    { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
    { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
    { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
    { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
    { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
  ];
  const countries = Maplace.locationsFromGeoJSON(await fetch("/examples/data/countries.json").then((response) => response.json()));

  // Each country in its colour, then its badge: in the shares' order, so the list is too.
  const locations = shares.flatMap(({ id, share, colour, badge }) => {
    const country = countries.find((location) => location.id === id);
    if (country === undefined) throw new Error(`countries.json has no ${id} to shade`);
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data, icon: badgeIcon },
    ];
  });
  maplace.setLocations(locations);

  // A click on a badge selects its country, as a click on its entry does.
  maplace.on("selectionChange", ({ id }) => {
    if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
  });
</script>
```

### Script on Google

`packages/maplace/examples/share-by-country/script.html`

```html
<!doctype html>
<!-- A page of your own script: the CDN script, what the map and its list mount on, and the map made with Maplace, which adds Maps JS with your key. -->
<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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../styles/share-by-country.css">
<style>
  #share-by-country-script-map-and-list { display: flex; height: 24rem; }
  #share-by-country-script-map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-script-list { display: contents; }
  #share-by-country-script-list .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-script-map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-script-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-script-map-and-list">
  <div id="share-by-country-script-map"></div>
  <div id="share-by-country-script-list"></div>
</div>
<script type="module">
  const span = (className, ...children) => {
    const element = document.createElement("span");
    element.className = className;
    element.append(...children);
    return element;
  };
  // A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in.
  const shareEntry = ({ location }) => {
    const { share, colour } = location.data;
    const dots = span("share-dots");
    dots.setAttribute("aria-hidden", "true");
    for (let tenth = 0; tenth < 10; tenth++) {
      const dot = span("share-dot");
      dot.toggleAttribute("data-filled", tenth < share / 10);
      dots.append(dot);
    }
    const entry = span("share-entry", span("share-head", span("share-name", location.title), span("share-figure", `${share}%`)), dots);
    entry.style.setProperty("--colour", colour);
    return entry;
  };
  // A country's share on the map: the figure in a ring of its colour.
  const badgeIcon = ({ data }) => {
    const badge = span("share-badge", `${data.share}%`);
    badge.style.setProperty("--colour", data.colour);
    return badge;
  };

  const maplace = Maplace.createGoogleMap("#share-by-country-script-map", {
    apiKey: "YOUR_KEY",
    view: { kind: "fit-all", padding: 48 },
    list: { container: "#share-by-country-script-list", heading: "Share by country", fitAll: true, fitAllLabel: "All countries", render: shareEntry },
  });

  // Each country's share, the colour it is drawn in, and where its badge sits. The shares are
  // made up, for the example.
  const shares = [
    { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
    { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
    { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
    { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
    { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
    { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
  ];
  const countries = Maplace.locationsFromGeoJSON(await fetch("/examples/data/countries.json").then((response) => response.json()));

  // Each country in its colour, then its badge: in the shares' order, so the list is too.
  const locations = shares.flatMap(({ id, share, colour, badge }) => {
    const country = countries.find((location) => location.id === id);
    if (country === undefined) throw new Error(`countries.json has no ${id} to shade`);
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data, icon: badgeIcon },
    ];
  });
  maplace.setLocations(locations);

  // A click on a badge selects its country, as a click on its entry does.
  maplace.on("selectionChange", ({ id }) => {
    if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/share-by-country/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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../../styles/share-by-country.css">
<style>
  #share-by-country-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #share-by-country-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-maplibre-vanilla-list { display: contents; }
  #share-by-country-maplibre-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-maplibre-vanilla-map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-maplibre-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-maplibre-vanilla-map-and-list">
  <div id="share-by-country-maplibre-vanilla-map"></div>
  <div id="share-by-country-maplibre-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/share-by-country/maplibre/vanilla.ts`

```ts
import "maplibre-gl/dist/maplibre-gl.css";
import { type ListEntry, type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createMapLibreMap } from "@maplacejs/maplace/maplibre";

/** What a country's shape and badge carry: its share, and the colour it is drawn in. */
interface CountryShare {
  readonly share: number;
  readonly colour: string;
}

// Each country's share, the colour it is drawn in, and where its badge sits. The shares are
// made up, for the example.
const SHARES = [
  { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
  { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
  { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
  { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
  { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
  { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
];

function span(className: string, ...children: (Node | string)[]): HTMLSpanElement {
  const element = document.createElement("span");
  element.className = className;
  element.append(...children);
  return element;
}

/** A country's share on the map: the figure in a ring of its colour. */
function badgeIcon({ data }: Location<CountryShare>): HTMLElement {
  const badge = span("share-badge", `${data?.share}%`);
  badge.style.setProperty("--colour", data?.colour ?? "");
  return badge;
}

/** A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in. */
function shareEntry({ location }: ListEntry<CountryShare>): Node {
  const { share = 0, colour = "" } = location.data ?? {};
  const dots = span("share-dots");
  dots.setAttribute("aria-hidden", "true");
  for (let tenth = 0; tenth < 10; tenth++) {
    const dot = span("share-dot");
    dot.toggleAttribute("data-filled", tenth < share / 10);
    dots.append(dot);
  }
  const entry = span(
    "share-entry",
    span("share-head", span("share-name", location.title ?? ""), span("share-figure", `${share}%`)),
    dots,
  );
  entry.style.setProperty("--colour", colour);
  return entry;
}

const maplace = createMapLibreMap<CountryShare>("#share-by-country-maplibre-vanilla-map", {
  view: { kind: "fit-all", padding: 48 },
  list: {
    container: "#share-by-country-maplibre-vanilla-list",
    heading: "Share by country",
    fitAll: true,
    fitAllLabel: "All countries",
    render: shareEntry,
  },
});

const countries = locationsFromGeoJSON(await (await fetch("/examples/data/countries.json")).json());

/** Each country in its colour, then its badge: in `SHARES`' order, so the list is too. */
const locations = SHARES.flatMap(({ id, share, colour, badge }): Location<CountryShare>[] => {
  const country = countries.find((location) => location.id === id);
  if (country?.type !== "polygon" && country?.type !== "multipolygon") {
    throw new Error(`countries.json has no ${id} to shade`);
  }
  const data = { share, colour };
  return [
    {
      ...country,
      data,
      style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
      hoveredStyle: { fillOpacity: 1 },
      selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
    },
    {
      id: `${id}-badge`,
      title: `${country.title}: ${share}%`,
      ...badge,
      listed: false,
      data,
      icon: badgeIcon,
    },
  ];
});

maplace.setLocations(locations);

// A click on a badge selects its country, as a click on its entry does.
maplace.on("selectionChange", ({ id }) => {
  if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
});
```

### Bundler on Google

`packages/maplace/examples/share-by-country/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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../styles/share-by-country.css">
<style>
  #share-by-country-vanilla-map-and-list { display: flex; height: 24rem; }
  #share-by-country-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-vanilla-list { display: contents; }
  #share-by-country-vanilla-list .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-vanilla-map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-vanilla-list .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-vanilla-map-and-list">
  <div id="share-by-country-vanilla-map"></div>
  <div id="share-by-country-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/share-by-country/vanilla.ts`

```ts
import { type ListEntry, type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createGoogleMap } from "@maplacejs/maplace/google";

/** What a country's shape and badge carry: its share, and the colour it is drawn in. */
interface CountryShare {
  readonly share: number;
  readonly colour: string;
}

// Each country's share, the colour it is drawn in, and where its badge sits. The shares are
// made up, for the example.
const SHARES = [
  { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
  { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
  { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
  { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
  { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
  { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
];

function span(className: string, ...children: (Node | string)[]): HTMLSpanElement {
  const element = document.createElement("span");
  element.className = className;
  element.append(...children);
  return element;
}

/** A country's share on the map: the figure in a ring of its colour. */
function badgeIcon({ data }: Location<CountryShare>): HTMLElement {
  const badge = span("share-badge", `${data?.share}%`);
  badge.style.setProperty("--colour", data?.colour ?? "");
  return badge;
}

/** A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in. */
function shareEntry({ location }: ListEntry<CountryShare>): Node {
  const { share = 0, colour = "" } = location.data ?? {};
  const dots = span("share-dots");
  dots.setAttribute("aria-hidden", "true");
  for (let tenth = 0; tenth < 10; tenth++) {
    const dot = span("share-dot");
    dot.toggleAttribute("data-filled", tenth < share / 10);
    dots.append(dot);
  }
  const entry = span(
    "share-entry",
    span("share-head", span("share-name", location.title ?? ""), span("share-figure", `${share}%`)),
    dots,
  );
  entry.style.setProperty("--colour", colour);
  return entry;
}

const maplace = createGoogleMap<CountryShare>("#share-by-country-vanilla-map", {
  view: { kind: "fit-all", padding: 48 },
  list: {
    container: "#share-by-country-vanilla-list",
    heading: "Share by country",
    fitAll: true,
    fitAllLabel: "All countries",
    render: shareEntry,
  },
});

const countries = locationsFromGeoJSON(await (await fetch("/examples/data/countries.json")).json());

/** Each country in its colour, then its badge: in `SHARES`' order, so the list is too. */
const locations = SHARES.flatMap(({ id, share, colour, badge }): Location<CountryShare>[] => {
  const country = countries.find((location) => location.id === id);
  if (country?.type !== "polygon" && country?.type !== "multipolygon") {
    throw new Error(`countries.json has no ${id} to shade`);
  }
  const data = { share, colour };
  return [
    {
      ...country,
      data,
      style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
      hoveredStyle: { fillOpacity: 1 },
      selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
    },
    {
      id: `${id}-badge`,
      title: `${country.title}: ${share}%`,
      ...badge,
      listed: false,
      data,
      icon: badgeIcon,
    },
  ];
});

maplace.setLocations(locations);

// A click on a badge selects its country, as a click on its entry does.
maplace.on("selectionChange", ({ id }) => {
  if (id?.endsWith("-badge")) maplace.select(id.replace(/-badge$/, ""));
});
```

### React on MapLibre

`packages/maplace/examples/share-by-country/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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../../styles/share-by-country.css">
<style>
  #share-by-country-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #share-by-country-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-maplibre-react-root .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-maplibre-react-root .map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-maplibre-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/share-by-country/maplibre/react.tsx`

```tsx
import "maplibre-gl/dist/maplibre-gl.css";
import { type ListEntry, type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { type CSSProperties, StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

/** What a country's shape and badge carry: its share, and the colour it is drawn in. */
interface CountryShare {
  readonly share: number;
  readonly colour: string;
}

// Each country's share, the colour it is drawn in, and where its badge sits. The shares are
// made up, for the example.
const SHARES = [
  { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
  { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
  { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
  { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
  { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
  { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
];

const FIRST_VIEW = { kind: "fit-all", padding: 48 } as const;

/** Each country in its colour, then its badge: in `SHARES`' order, so the list is too. */
function sharesOn(countries: readonly Location[]): Location<CountryShare>[] {
  return SHARES.flatMap(({ id, share, colour, badge }): Location<CountryShare>[] => {
    const country = countries.find((location) => location.id === id);
    if (country?.type !== "polygon" && country?.type !== "multipolygon") {
      throw new Error(`countries.json has no ${id} to shade`);
    }
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data },
    ];
  });
}

const colourOf = (colour = "") => ({ "--colour": colour }) as CSSProperties;

/** A country's share on the map: the figure in a ring of its colour. */
const badgeIcon = ({ data }: Location<CountryShare>) => (
  <span className="share-badge" style={colourOf(data?.colour)}>
    {data?.share}%
  </span>
);

/** A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in. */
const shareEntry = ({ location }: ListEntry<CountryShare>) => {
  const { share = 0, colour = "" } = location.data ?? {};
  return (
    <span className="share-entry" style={colourOf(colour)}>
      <span className="share-head">
        <span className="share-name">{location.title}</span>
        <span className="share-figure">{share}%</span>
      </span>
      <span className="share-dots" aria-hidden="true">
        {Array.from({ length: 10 }, (_, tenth) => (
          // biome-ignore lint/suspicious/noArrayIndexKey: ten dots in a fixed row, by place.
          <span key={tenth} className="share-dot" data-filled={tenth < share / 10 || undefined} />
        ))}
      </span>
    </span>
  );
};

function ShareByCountry() {
  const [locations, setLocations] = useState<readonly Location<CountryShare>[]>([]);
  const [selectedId, setSelectedId] = useState<string>();
  useEffect(() => {
    fetch("/examples/data/countries.json")
      .then((response) => response.json())
      .then((collection) => setLocations(sharesOn(locationsFromGeoJSON(collection))));
  }, []);
  return (
    <MaplaceProvider
      locations={locations}
      view={FIRST_VIEW}
      selectedId={selectedId}
      // A click on a badge selects its country, as a click on its entry does.
      onSelectionChange={({ id }) => setSelectedId(id?.replace(/-badge$/, ""))}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createMapLibreAdapter} className="map" markerIcon={badgeIcon} />
        <LocationList heading="Share by country" fitAll fitAllLabel="All countries">
          {shareEntry}
        </LocationList>
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("share-by-country-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <ShareByCountry />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/share-by-country/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/share-by-country.css, which every version links. -->
<link rel="stylesheet" href="../styles/share-by-country.css">
<style>
  #share-by-country-react-root .map-and-list { display: flex; height: 24rem; }
  #share-by-country-react-root .map { flex: 1 1 auto; min-width: 0; }
  #share-by-country-react-root .maplace-list-view { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size. */
  @media (width < 40rem) {
    #share-by-country-react-root .map-and-list { flex-direction: column; height: 36rem; }
    #share-by-country-react-root .maplace-list-view { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="share-by-country-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/share-by-country/react.tsx`

```tsx
import { type ListEntry, type Location, locationsFromGeoJSON } from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { type CSSProperties, StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

/** What a country's shape and badge carry: its share, and the colour it is drawn in. */
interface CountryShare {
  readonly share: number;
  readonly colour: string;
}

// Each country's share, the colour it is drawn in, and where its badge sits. The shares are
// made up, for the example.
const SHARES = [
  { id: "USA", share: 30, colour: "#1d4ed8", badge: { lat: 33, lng: -98 } },
  { id: "IND", share: 20, colour: "#c2410c", badge: { lat: 16, lng: 78 } },
  { id: "GBR", share: 20, colour: "#15803d", badge: { lat: 51, lng: -1.5 } },
  { id: "BRA", share: 10, colour: "#6d28d9", badge: { lat: -16, lng: -52 } },
  { id: "SAU", share: 10, colour: "#b45309", badge: { lat: 19, lng: 45 } },
  { id: "AUS", share: 10, colour: "#be185d", badge: { lat: -31, lng: 134 } },
];

const FIRST_VIEW = { kind: "fit-all", padding: 48 } as const;

/** Each country in its colour, then its badge: in `SHARES`' order, so the list is too. */
function sharesOn(countries: readonly Location[]): Location<CountryShare>[] {
  return SHARES.flatMap(({ id, share, colour, badge }): Location<CountryShare>[] => {
    const country = countries.find((location) => location.id === id);
    if (country?.type !== "polygon" && country?.type !== "multipolygon") {
      throw new Error(`countries.json has no ${id} to shade`);
    }
    const data = { share, colour };
    return [
      {
        ...country,
        data,
        style: { fill: colour, fillOpacity: 0.85, stroke: "#ffffff", strokeWidth: 1 },
        hoveredStyle: { fillOpacity: 1 },
        selectedStyle: { fillOpacity: 1, stroke: "#111827", strokeWidth: 2 },
      },
      { id: `${id}-badge`, title: `${country.title}: ${share}%`, ...badge, listed: false, data },
    ];
  });
}

const colourOf = (colour = "") => ({ "--colour": colour }) as CSSProperties;

/** A country's share on the map: the figure in a ring of its colour. */
const badgeIcon = ({ data }: Location<CountryShare>) => (
  <span className="share-badge" style={colourOf(data?.colour)}>
    {data?.share}%
  </span>
);

/** A country in the list: its name with its colour's swatch and its share, then ten dots, the share filled in. */
const shareEntry = ({ location }: ListEntry<CountryShare>) => {
  const { share = 0, colour = "" } = location.data ?? {};
  return (
    <span className="share-entry" style={colourOf(colour)}>
      <span className="share-head">
        <span className="share-name">{location.title}</span>
        <span className="share-figure">{share}%</span>
      </span>
      <span className="share-dots" aria-hidden="true">
        {Array.from({ length: 10 }, (_, tenth) => (
          // biome-ignore lint/suspicious/noArrayIndexKey: ten dots in a fixed row, by place.
          <span key={tenth} className="share-dot" data-filled={tenth < share / 10 || undefined} />
        ))}
      </span>
    </span>
  );
};

function ShareByCountry() {
  const [locations, setLocations] = useState<readonly Location<CountryShare>[]>([]);
  const [selectedId, setSelectedId] = useState<string>();
  useEffect(() => {
    fetch("/examples/data/countries.json")
      .then((response) => response.json())
      .then((collection) => setLocations(sharesOn(locationsFromGeoJSON(collection))));
  }, []);
  return (
    <MaplaceProvider
      locations={locations}
      view={FIRST_VIEW}
      selectedId={selectedId}
      // A click on a badge selects its country, as a click on its entry does.
      onSelectionChange={({ id }) => setSelectedId(id?.replace(/-badge$/, ""))}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map" markerIcon={badgeIcon} />
        <LocationList heading="Share by country" fitAll fitAllLabel="All countries">
          {shareEntry}
        </LocationList>
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("share-by-country-react-root") as HTMLElement).render(
  <StrictMode>
    <ShareByCountry />
  </StrictMode>,
);
```

### The stylesheet every version links

`packages/maplace/examples/styles/share-by-country.css`

```css
/* The share-by-country example's look, which every version links: page, script, vanilla and
   React, on either map. Each country's colour comes with its data, as --colour. */
/* A country's share on the map: a ring in its colour around the figure, standing on its place. */
.share-badge {
  display: grid;
  place-items: center;
  width: 3rem;
  height: 3rem;
  border: 4px solid var(--colour);
  border-radius: 50%;
  background: #fff;
  color: #111;
  font:
    700 0.875rem / 1 system-ui,
    sans-serif;
  box-shadow: 0 2px 8px rgb(0 0 0 / 0.25);
}
.share-badge[data-hovered],
[data-hovered] > .share-badge {
  outline: 2px solid #111;
}
/* On a phone the badge is smaller, so neighbours stay apart. */
@media (width < 40rem) {
  .share-badge {
    width: 2.25rem;
    height: 2.25rem;
    border-width: 3px;
    font-size: 0.6875rem;
  }
}
/* A country in the list: its name by a swatch of its colour and its share on one line, then a row
   of ten dots under the name, its share filled in. */
.share-entry {
  display: grid;
  gap: 0.375rem;
}
.share-head {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 0.75rem;
}
.share-name {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  font-weight: 500;
}
.share-name::before {
  content: "";
  flex: none;
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 0.125rem;
  background: var(--colour);
}
.share-figure {
  font-weight: 500;
  font-variant-numeric: tabular-nums;
}
/* Under the name, past its swatch. */
.share-dots {
  display: flex;
  gap: 0.1875rem;
  margin-inline-start: 1rem;
}
.share-dot {
  width: 0.4375rem;
  height: 0.4375rem;
  border-radius: 50%;
  background: #e4e4e0;
}
.share-dot[data-filled] {
  background: var(--colour);
}
```
