# Live data, clusters and routes on Google Maps and MapLibre

Locations fetched as JSON and swapped in live, markers grouped into clusters that show a count, the world's countries shaded by a value, a month of earthquakes as a heatmap, a map that loads only when the visitor presses a button, a link that opens the map on a place, and a driving route through your stops.

Data fetched and swapped in live, thousands of points clustered, countries shaded by a value, a heatmap of earthquakes, a drive through your places, a map loaded on a press, a link to a place.

## Live data from JSON

Data sets, fetched and swapped in live: markers, an area, a circle, and on Google a route.

Data sets your page fetches and swaps in while the map stays: markers, an area, a circle, and on Google a route through some of them. The map's element never fetches anything itself.

- **Try it**: press each button above the map, Markers, More markers, Area and Circle: the map and the list take the new set, and the map fits it. On Google a fifth, Route, draws a route through its places, and leaving that set takes its route with it; MapLibre, which routes only through your own routing and has no route stored for these places, has no such button. A slower answer to an earlier press is dropped.
- **HTML**: `list` on an empty `<maplace-map>`, and a script assigning the `locations` property, and on Google `route` ([Properties and methods](/element/#properties-and-methods)), then calling `maplace.fitAll()`.
- **Script** and **Bundler**: [`setLocations` and `fitAll`](/store/#methods) on the store `createGoogleMap` or `createMapLibreMap` returns, and on Google `setRoute`.
- **React**: `locations` as a prop of `<MaplaceProvider>`, and on Google `route`, from your state ([`<MaplaceProvider>`](/react/#maplaceprovider)), and a small component calling `fitAll` through [`useMaplace()`](/react/#usemaplace) when they change.


### HTML on MapLibre

`packages/maplace/examples/live-data/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- Four data sets, each fetched by the page and swapped in live: markers, an area and a circle.
     The Google version's fifth, a route, isn't here: MapLibre routes through your own routing,
     and this example has no route stored for its places (the route example has one). -->
<style>
  #live-data-maplibre-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
</style>
<p id="live-data-maplibre-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<maplace-map id="live-data-maplibre-map" list></maplace-map>
<script type="module">
  const map = document.getElementById('live-data-maplibre-map');
  const buttons = document.querySelectorAll('#live-data-maplibre-groups button');
  let latestGroup;

  /** Swaps in the group last asked for: a slower answer to an earlier click is dropped. */
  async function showGroup(letter) {
    latestGroup = letter;
    for (const button of buttons) button.setAttribute('aria-pressed', String(button.value === letter));
    const response = await fetch(`/examples/data/live-data-${letter}.json`);
    const locations = await response.json();
    if (letter !== latestGroup) return;
    map.locations = locations;
    map.maplace.fitAll();
  }

  for (const button of buttons) {
    button.addEventListener('click', () => showGroup(button.value));
  }
  await showGroup('a');
</script>
```

### HTML on Google

`packages/maplace/examples/live-data/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- Five data sets, each fetched by the page and swapped in live: markers, markers with a route
     through them, an area and a circle; leaving the route's set takes its route with it. -->
<style>
  #live-data-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
</style>
<p id="live-data-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="c">Route</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<maplace-map id="live-data-map" api-key="YOUR_KEY" list></maplace-map>
<script type="module">
  const map = document.getElementById('live-data-map');
  const buttons = document.querySelectorAll('#live-data-groups button');
  let latestGroup;

  /** Swaps in the group last asked for: a slower answer to an earlier click is dropped. */
  async function showGroup(letter) {
    latestGroup = letter;
    for (const button of buttons) button.setAttribute('aria-pressed', String(button.value === letter));
    const response = await fetch(`/examples/data/live-data-${letter}.json`);
    const locations = await response.json();
    if (letter !== latestGroup) return;
    map.locations = locations;
    if (letter === 'c') map.route = { stops: locations.map(({ id }) => id), travelMode: 'driving' };
    map.maplace.fitAll();
  }

  for (const button of buttons) {
    button.addEventListener('click', () => showGroup(button.value));
  }
  await showGroup('a');
</script>
```

### Script on MapLibre

`packages/maplace/examples/live-data/maplibre/script.html`

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet, the group buttons and what the map and its list mount on, and the map made with Maplace; its data sets come from live-data-a.json, -b, -d and -e (no route is stored for its places on MapLibre, so no route's set, -c). -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #live-data-maplibre-script-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #live-data-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #live-data-maplibre-script-list { display: contents; }
  #live-data-maplibre-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-maplibre-script-map-and-list { flex-direction: column; }
    #live-data-maplibre-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<p id="live-data-maplibre-script-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<div id="live-data-maplibre-script-map-and-list">
  <div id="live-data-maplibre-script-map"></div>
  <div id="live-data-maplibre-script-list"></div>
</div>
<script type="module">
  const maplace = Maplace.createMapLibreMap("#live-data-maplibre-script-map", {
    list: { container: "#live-data-maplibre-script-list" },
  });

  let latestGroup;

  const buttons = document.querySelectorAll("#live-data-maplibre-script-groups button");
  for (const button of buttons) {
    button.addEventListener("click", () => showGroup(button.value));
  }
  await showGroup("a");

  /**
   * One of the data sets swapped in. Only the group last asked for: a slower answer to an earlier
   * click is dropped.
   */
  async function showGroup(letter) {
    latestGroup = letter;
    for (const button of buttons)
      button.setAttribute("aria-pressed", String(button.value === letter));
    const response = await fetch(`/examples/data/live-data-${letter}.json`);
    const locations = await response.json();
    if (letter !== latestGroup) return;
    maplace.setLocations(locations);
    maplace.fitAll();
  }
</script>
```

### Script on Google

`packages/maplace/examples/live-data/script.html`

```html
<!doctype html>
<!-- A page of your own script: the CDN script, the group buttons and what the map and its list mount on, and the map made with Maplace, which adds Maps JS with your key; its data sets come from live-data-a.json to live-data-e.json. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  #live-data-script-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-script-map-and-list { display: flex; height: 24rem; }
  #live-data-script-map { flex: 1 1 auto; min-width: 0; }
  #live-data-script-list { display: contents; }
  #live-data-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-script-map-and-list { flex-direction: column; }
    #live-data-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<p id="live-data-script-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="c">Route</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<div id="live-data-script-map-and-list">
  <div id="live-data-script-map"></div>
  <div id="live-data-script-list"></div>
</div>
<script type="module">
  const maplace = Maplace.createGoogleMap("#live-data-script-map", {
    apiKey: "YOUR_KEY",
    list: { container: "#live-data-script-list" },
  });

  let latestGroup;

  const buttons = document.querySelectorAll("#live-data-script-groups button");
  for (const button of buttons) {
    button.addEventListener("click", () => showGroup(button.value));
  }
  await showGroup("a");

  /**
   * One of the data sets swapped in, the route's (c) with a route through it; leaving it takes
   * the route away. Only the group last asked for: a slower answer to an earlier click is dropped.
   */
  async function showGroup(letter) {
    latestGroup = letter;
    for (const button of buttons)
      button.setAttribute("aria-pressed", String(button.value === letter));
    const response = await fetch(`/examples/data/live-data-${letter}.json`);
    const locations = await response.json();
    if (letter !== latestGroup) return;
    maplace.setLocations(locations);
    if (letter === "c") {
      maplace.setRoute({ stops: locations.map(({ id }) => id), travelMode: "driving" });
    }
    maplace.fitAll();
  }
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/live-data/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. -->
<style>
  #live-data-maplibre-vanilla-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #live-data-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #live-data-maplibre-vanilla-list { display: contents; }
  #live-data-maplibre-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-maplibre-vanilla-map-and-list { flex-direction: column; }
    #live-data-maplibre-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<p id="live-data-maplibre-vanilla-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<div id="live-data-maplibre-vanilla-map-and-list">
  <div id="live-data-maplibre-vanilla-map"></div>
  <div id="live-data-maplibre-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/live-data/maplibre/vanilla.ts`

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

const maplace = createMapLibreMap("#live-data-maplibre-vanilla-map", {
  list: { container: "#live-data-maplibre-vanilla-list" },
});

let latestGroup: string | undefined;

const buttons = document.querySelectorAll<HTMLButtonElement>(
  "#live-data-maplibre-vanilla-groups button",
);
for (const button of buttons) {
  button.addEventListener("click", () => showGroup(button.value));
}
await showGroup("a");

/**
 * One of the data sets swapped in. Only the group last asked for: a slower answer to an earlier
 * click is dropped.
 */
async function showGroup(letter: string): Promise<void> {
  latestGroup = letter;
  for (const button of buttons)
    button.setAttribute("aria-pressed", String(button.value === letter));
  const response = await fetch(`/examples/data/live-data-${letter}.json`);
  const locations: Location[] = await response.json();
  if (letter !== latestGroup) return;
  maplace.setLocations(locations);
  maplace.fitAll();
}
```

### Bundler on Google

`packages/maplace/examples/live-data/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>
<style>
  #live-data-vanilla-groups [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-vanilla-map-and-list { display: flex; height: 24rem; }
  #live-data-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #live-data-vanilla-list { display: contents; }
  #live-data-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-vanilla-map-and-list { flex-direction: column; }
    #live-data-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<p id="live-data-vanilla-groups">
  <button type="button" value="a">Markers</button>
  <button type="button" value="b">More markers</button>
  <button type="button" value="c">Route</button>
  <button type="button" value="d">Area</button>
  <button type="button" value="e">Circle</button>
</p>
<div id="live-data-vanilla-map-and-list">
  <div id="live-data-vanilla-map"></div>
  <div id="live-data-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/live-data/vanilla.ts`

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

const maplace = createGoogleMap("#live-data-vanilla-map", {
  list: { container: "#live-data-vanilla-list" },
});

let latestGroup: string | undefined;

const buttons = document.querySelectorAll<HTMLButtonElement>("#live-data-vanilla-groups button");
for (const button of buttons) {
  button.addEventListener("click", () => showGroup(button.value));
}
await showGroup("a");

/**
 * One of the data sets swapped in, the route's (c) with a route through it; leaving it takes
 * the route away. Only the group last asked for: a slower answer to an earlier click is dropped.
 */
async function showGroup(letter: string): Promise<void> {
  latestGroup = letter;
  for (const button of buttons)
    button.setAttribute("aria-pressed", String(button.value === letter));
  const response = await fetch(`/examples/data/live-data-${letter}.json`);
  const locations: Location[] = await response.json();
  if (letter !== latestGroup) return;
  maplace.setLocations(locations);
  if (letter === "c") {
    maplace.setRoute({ stops: locations.map(({ id }) => id), travelMode: "driving" });
  }
  maplace.fitAll();
}
```

### React on MapLibre

`packages/maplace/examples/live-data/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. -->
<style>
  #live-data-maplibre-react-root [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #live-data-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #live-data-maplibre-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-maplibre-react-root .map-and-list { flex-direction: column; }
    #live-data-maplibre-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="live-data-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/live-data/maplibre/react.tsx`

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

/** Each data set's button, by its file's letter: `/examples/data/live-data-a.json` is the markers. */
const GROUPS = { a: "Markers", b: "More markers", d: "Area", e: "Circle" };

const NO_LOCATIONS: readonly Location[] = [];

/** A data set: on MapLibre, with no route stored for its places, there is no route's set (c). */
async function fetchGroup(letter: string): Promise<Location[]> {
  const response = await fetch(`/examples/data/live-data-${letter}.json`);
  return response.json();
}

/** Fits the map to every location each time a data set is swapped in. */
function FitAllOnSwap({ locations }: { readonly locations: readonly Location[] }) {
  const maplace = useMaplace();
  useEffect(() => {
    if (locations.length > 0) maplace.fitAll();
  }, [maplace, locations]);
  return null;
}

function LiveData() {
  const [group, setGroup] = useState("a");
  const [locations, setLocations] = useState(NO_LOCATIONS);
  // Only the group last asked for: a slower answer to an earlier click is dropped.
  useEffect(() => {
    let latest = true;
    fetchGroup(group).then((fetched) => latest && setLocations(fetched));
    return () => {
      latest = false;
    };
  }, [group]);
  return (
    <MaplaceProvider locations={locations}>
      <p>
        {/* A space after each button, as between buttons written in HTML. */}
        {Object.entries(GROUPS).map(([letter, label]) => (
          <Fragment key={letter}>
            <button type="button" aria-pressed={letter === group} onClick={() => setGroup(letter)}>
              {label}
            </button>{" "}
          </Fragment>
        ))}
      </p>
      <FitAllOnSwap locations={locations} />
      <div className="map-and-list">
        <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
        <LocationList />
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("live-data-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <LiveData />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/live-data/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>
<style>
  #live-data-react-root [aria-pressed="true"] { background: CanvasText; color: Canvas; }
  #live-data-react-root .map-and-list { display: flex; height: 24rem; }
  #live-data-react-root .map { flex: 1 1 auto; min-width: 0; }
  #live-data-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #live-data-react-root .map-and-list { flex-direction: column; }
    #live-data-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="live-data-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/live-data/react.tsx`

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

/** Each data set's button, by its file's letter: `/examples/data/live-data-a.json` is the markers. */
const GROUPS = { a: "Markers", b: "More markers", c: "Route", d: "Area", e: "Circle" };

/** A data set shown, the route's (c) with a route through it. */
interface Shown {
  readonly locations: readonly Location[];
  readonly route: Route | undefined;
}

const NOTHING: Shown = { locations: [], route: undefined };

async function fetchGroup(letter: string): Promise<Shown> {
  const response = await fetch(`/examples/data/live-data-${letter}.json`);
  const locations: Location[] = await response.json();
  const stops = locations.map(({ id }) => id);
  return { locations, route: letter === "c" ? { stops, travelMode: "driving" } : undefined };
}

/** Fits the map to every location each time a data set is swapped in. */
function FitAllOnSwap({ locations }: { readonly locations: readonly Location[] }) {
  const maplace = useMaplace();
  useEffect(() => {
    if (locations.length > 0) maplace.fitAll();
  }, [maplace, locations]);
  return null;
}

function LiveData() {
  const [group, setGroup] = useState("a");
  const [shown, setShown] = useState(NOTHING);
  // Only the group last asked for: a slower answer to an earlier click is dropped.
  useEffect(() => {
    let latest = true;
    fetchGroup(group).then((fetched) => latest && setShown(fetched));
    return () => {
      latest = false;
    };
  }, [group]);
  return (
    <MaplaceProvider locations={shown.locations} route={shown.route}>
      <p>
        {/* A space after each button, as between buttons written in HTML. */}
        {Object.entries(GROUPS).map(([letter, label]) => (
          <Fragment key={letter}>
            <button type="button" aria-pressed={letter === group} onClick={() => setGroup(letter)}>
              {label}
            </button>{" "}
          </Fragment>
        ))}
      </p>
      <FitAllOnSwap locations={shown.locations} />
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
        <LocationList />
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("live-data-react-root") as HTMLElement).render(
  <StrictMode>
    <LiveData />
  </StrictMode>,
);
```

## Marker clustering

4,000 points, those near each other drawn as one badge counting them.

4,000 points fetched by the page: those near each other are drawn as one badge counting them, so the map stays fast and readable.

- **Try it**: zoom in on a badge, and it splits into smaller badges, then single pins.
- **HTML**: `cluster` on `<maplace-map>`, on a CDN script that bundles clustering: `maplace-element-cluster.iife.js` on Google, while MapLibre's script always does ([Map attributes](/element/#map-attributes)). The element never fetches: a script assigns `locations`.
- **Script** and **Bundler**: `cluster: true` in the map's options, then [`setLocations`](/store/#methods) with the points ([Options](/store/#options)). The Script version on Google is on the same cluster script; from npm, each provider loads its clustering only for a map that clusters ([on Google](/google/#clustering), [on MapLibre](/maplibre/#clustering)).
- **React**: the `cluster` prop of `<MaplaceProvider>` ([`<MaplaceProvider>`](/react/#maplaceprovider)).
- **Their look**: [Cluster badges](/styling/#cluster-badges) has the badge's colours, as [Brand colours](/examples/styling/#brand) uses them.
- **With a list**: a list of every point is too long to use; one that lists only what is in the map's view is in [This area](/examples/lists/#this-area).


### HTML on MapLibre

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- 4,000 points, clustered (the MapLibre build bundles its clustering): the markers near each other drawn as one badge counting them, which splits as you zoom in. -->
<maplace-map id="big-maplibre-map" cluster></maplace-map>
<script type="module">
  const response = await fetch('/examples/data/points-4k.json');
  document.getElementById('big-maplibre-map').locations = await response.json();
</script>
```

### HTML on Google

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-cluster.iife.js"></script>
<!-- 4,000 points, clustered (the cluster build bundles @googlemaps/markerclusterer): the markers near each other drawn as one badge counting them, which splits as you zoom in. -->
<maplace-map id="big-map" api-key="YOUR_KEY" cluster></maplace-map>
<script type="module">
  const response = await fetch('/examples/data/points-4k.json');
  document.getElementById('big-map').locations = await response.json();
</script>
```

### Script on MapLibre

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

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl, its stylesheet and its clustering, what the map mounts on, and the map made with Maplace; its 4,000 points come from points-4k.json. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #big-maplibre-script-map { height: 24rem; }
</style>
<div id="big-maplibre-script-map"></div>
<script type="module">
  const maplace = Maplace.createMapLibreMap("#big-maplibre-script-map", {
    cluster: true,
  });

  const response = await fetch("/examples/data/points-4k.json");
  const points = await response.json();
  maplace.setLocations(points);
</script>
```

### Script on Google

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

```html
<!doctype html>
<!-- A page of your own script: the cluster CDN script, which bundles @googlemaps/markerclusterer, what the map mounts on, and the map made with Maplace, which adds Maps JS with your key; its 4,000 points come from points-4k.json. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-cluster.iife.js"></script>
<style>
  #big-script-map { height: 24rem; }
</style>
<div id="big-script-map"></div>
<script type="module">
  const maplace = Maplace.createGoogleMap("#big-script-map", {
    apiKey: "YOUR_KEY",
    cluster: true,
  });

  const response = await fetch("/examples/data/points-4k.json");
  const points = await response.json();
  maplace.setLocations(points);
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/big/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. -->
<style>
  #big-maplibre-vanilla-map { height: 24rem; }
</style>
<div id="big-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const maplace = createMapLibreMap("#big-maplibre-vanilla-map", {
  cluster: true,
});

const response = await fetch("/examples/data/points-4k.json");
const points: Location[] = await response.json();
maplace.setLocations(points);
```

### Bundler on Google

`packages/maplace/examples/big/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>
<style>
  #big-vanilla-map { height: 24rem; }
</style>
<div id="big-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const maplace = createGoogleMap("#big-vanilla-map", {
  cluster: true,
});

const response = await fetch("/examples/data/points-4k.json");
const points: Location[] = await response.json();
maplace.setLocations(points);
```

### React on MapLibre

`packages/maplace/examples/big/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. -->
<style>
  #big-maplibre-react-root .map { height: 24rem; }
</style>
<div id="big-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

function Big() {
  const [points, setPoints] = useState<readonly Location[]>([]);
  useEffect(() => {
    fetch("/examples/data/points-4k.json")
      .then((response) => response.json())
      .then(setPoints);
  }, []);
  return (
    <MaplaceProvider locations={points} cluster>
      <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("big-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <Big />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/big/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>
<style>
  #big-react-root .map { height: 24rem; }
</style>
<div id="big-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

function Big() {
  const [points, setPoints] = useState<readonly Location[]>([]);
  useEffect(() => {
    fetch("/examples/data/points-4k.json")
      .then((response) => response.json())
      .then(setPoints);
  }, []);
  return (
    <MaplaceProvider locations={points} cluster>
      <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("big-react-root") as HTMLElement).render(
  <StrictMode>
    <Big />
  </StrictMode>,
);
```

## Choropleth of the world

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

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.

- **Try it**: hover a country for its value; Alaska lights up the whole United States. Pick a country in the legend's select, from the keyboard too, and the map shows it, at its largest polygon: France, not French Guiana. On a touch screen a tap shows the value.
- **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`, as the element never fetches.
- **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.


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

## Heatmaps

A month of earthquakes as a heatmap by magnitude, dots when zoomed in, volcanoes as pins, a checkbox for each.

A month of earthquakes of magnitude 4.5 and up, drawn as a heatmap weighted by magnitude, with a dozen volcanoes as pins: the quakes are locations as any other, so the list's search and its checkbox for each group narrow the heat with them.

- **Try it**: zoom in on Japan or Chile: over two zooms the heat fades into a dot per quake, sized and coloured by its magnitude, and a click on a dot selects its quake in the list. Type "Japan" in the search box: the heat shrinks to Japan's quakes, and the volcanoes leave the map. Open Groups and untick Quakes: the heat goes, the volcanoes stay; the checkboxes keep what the search found, as they set only the filter's groups ([List view options](/store/#list-view-options)).
- **The data**: `earthquakes.json`, a month of the USGS's earthquakes of magnitude 4.5 and up, to November 2026 (public domain), each with its magnitude as `weight`; `volcanoes.json`, a dozen well-known volcanoes.
- **HTML**: `heatmap="Quakes"` on `<maplace-map>` draws the markers of the group `Quakes` as heat, `group-filter` adds a Groups button above the list that opens the checkboxes, and `heatmap-max-zoom` sets where it gives way to the dots ([Map attributes](/element/#map-attributes)); a quake's `weight` is its magnitude.
- **Script** and **Bundler**: `heatmap: { groups: ["Quakes"] }` in the map's options, `maxZoom` beside it ([Heatmaps](/store/#heatmaps)), `groupFilter: true` in its `list`, and `weight` on each quake ([Markers](/locations/#markers)).
- **React**: the same `heatmap` on `<MaplaceProvider>`, beside a `<LocationList search groupFilter>` ([`<LocationList>`](/react/#locationlist)).
- **On both providers**: MapLibre draws the heat and the dots in its own layers, under the pins; Google, on a canvas over the map, the dots as markers. A marker in the heat has no `icon` and isn't `editable`: it is drawn as heat and a dot.


### HTML on MapLibre

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-maplibre-map { height: 36rem; }
    #earthquakes-maplibre-map > .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<!-- A month of earthquakes of magnitude 4.5 and up, to November 2026 (USGS, in earthquakes.json), as a heatmap weighted by magnitude, with volcanoes (volcanoes.json) as pins: zoomed in, the heat fades into a dot per quake, and the list's search and its checkbox for each group narrow the heat with it. -->
<maplace-map id="earthquakes-maplibre-map" heatmap="Quakes" center="20,160" zoom="2" list search
  search-label="Find a quake or a volcano" group-filter></maplace-map>
<script type="module">
  // The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
  const [quakes, volcanoes] = await Promise.all([
    fetch("/examples/data/earthquakes.json").then((response) => response.json()),
    fetch("/examples/data/volcanoes.json").then((response) => response.json()),
  ]);
  document.getElementById("earthquakes-maplibre-map").locations = [...quakes, ...volcanoes];
</script>
```

### HTML on Google

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-map { height: 36rem; }
    #earthquakes-map > .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<!-- A month of earthquakes of magnitude 4.5 and up, to November 2026 (USGS, in earthquakes.json), as a heatmap weighted by magnitude, with volcanoes (volcanoes.json) as pins: zoomed in, the heat fades into a dot per quake, and the list's search and its checkbox for each group narrow the heat with it. -->
<maplace-map id="earthquakes-map" api-key="YOUR_KEY" heatmap="Quakes" center="20,160" zoom="2" list search
  search-label="Find a quake or a volcano" group-filter></maplace-map>
<script type="module">
  // The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
  const [quakes, volcanoes] = await Promise.all([
    fetch("/examples/data/earthquakes.json").then((response) => response.json()),
    fetch("/examples/data/volcanoes.json").then((response) => response.json()),
  ]);
  document.getElementById("earthquakes-map").locations = [...quakes, ...volcanoes];
</script>
```

### Script on MapLibre

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

```html
<!doctype html>
<!-- A page of your own script: the MapLibre CDN script, which bundles maplibre-gl and its stylesheet and what the map and its list mount on, and the map made with Maplace; the quakes as a heatmap by magnitude, the volcanoes as pins. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #earthquakes-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #earthquakes-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-maplibre-script-list { display: contents; }
  #earthquakes-maplibre-script-list .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-maplibre-script-map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-maplibre-script-list .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-maplibre-script-map-and-list">
  <div id="earthquakes-maplibre-script-map"></div>
  <div id="earthquakes-maplibre-script-list"></div>
</div>
<script type="module">
  // The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
  const [quakes, volcanoes] = await Promise.all([
    fetch("/examples/data/earthquakes.json").then((response) => response.json()),
    fetch("/examples/data/volcanoes.json").then((response) => response.json()),
  ]);
  Maplace.createMapLibreMap("#earthquakes-maplibre-script-map", {
    locations: [...quakes, ...volcanoes],
    heatmap: { groups: ["Quakes"] },
    view: { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 },
    list: {
      container: "#earthquakes-maplibre-script-list",
      search: true,
      searchLabel: "Find a quake or a volcano",
      groupFilter: true,
    },
  });
</script>
```

### Script on Google

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

```html
<!doctype html>
<!-- A page of your own script: the CDN script and what the map and its list mount on, and the map made with Maplace, which adds Maps JS with your key; the quakes as a heatmap by magnitude, the volcanoes as pins. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  #earthquakes-script-map-and-list { display: flex; height: 24rem; }
  #earthquakes-script-map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-script-list { display: contents; }
  #earthquakes-script-list .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-script-map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-script-list .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-script-map-and-list">
  <div id="earthquakes-script-map"></div>
  <div id="earthquakes-script-list"></div>
</div>
<script type="module">
  // The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
  const [quakes, volcanoes] = await Promise.all([
    fetch("/examples/data/earthquakes.json").then((response) => response.json()),
    fetch("/examples/data/volcanoes.json").then((response) => response.json()),
  ]);
  Maplace.createGoogleMap("#earthquakes-script-map", {
    apiKey: "YOUR_KEY",
    locations: [...quakes, ...volcanoes],
    heatmap: { groups: ["Quakes"] },
    view: { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 },
    list: {
      container: "#earthquakes-script-list",
      search: true,
      searchLabel: "Find a quake or a volcano",
      groupFilter: true,
    },
  });
</script>
```

### Bundler on MapLibre

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

```html
<!doctype html>
<!-- The page vanilla.ts runs on: what the map and its list mount on, and the module, which brings maplibre-gl and its stylesheet. -->
<style>
  #earthquakes-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #earthquakes-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-maplibre-vanilla-list { display: contents; }
  #earthquakes-maplibre-vanilla-list .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-maplibre-vanilla-map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-maplibre-vanilla-list .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-maplibre-vanilla-map-and-list">
  <div id="earthquakes-maplibre-vanilla-map"></div>
  <div id="earthquakes-maplibre-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

async function fetched(url: string): Promise<Location[]> {
  return (await fetch(url)).json();
}

// The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
const [quakes, volcanoes] = await Promise.all([
  fetched("/examples/data/earthquakes.json"),
  fetched("/examples/data/volcanoes.json"),
]);

createMapLibreMap("#earthquakes-maplibre-vanilla-map", {
  locations: [...quakes, ...volcanoes],
  heatmap: { groups: ["Quakes"] },
  view: { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 },
  list: {
    container: "#earthquakes-maplibre-vanilla-list",
    search: true,
    searchLabel: "Find a quake or a volcano",
    groupFilter: true,
  },
});
```

### Bundler on Google

`packages/maplace/examples/earthquakes/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>
<style>
  #earthquakes-vanilla-map-and-list { display: flex; height: 24rem; }
  #earthquakes-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-vanilla-list { display: contents; }
  #earthquakes-vanilla-list .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-vanilla-map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-vanilla-list .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-vanilla-map-and-list">
  <div id="earthquakes-vanilla-map"></div>
  <div id="earthquakes-vanilla-list"></div>
</div>
<script type="module" src="./vanilla.ts"></script>
```

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

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

async function fetched(url: string): Promise<Location[]> {
  return (await fetch(url)).json();
}

// The quakes, each weighing its magnitude, in the group the heatmap draws; the volcanoes, pins.
const [quakes, volcanoes] = await Promise.all([
  fetched("/examples/data/earthquakes.json"),
  fetched("/examples/data/volcanoes.json"),
]);

createGoogleMap("#earthquakes-vanilla-map", {
  locations: [...quakes, ...volcanoes],
  heatmap: { groups: ["Quakes"] },
  view: { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 },
  list: {
    container: "#earthquakes-vanilla-list",
    search: true,
    searchLabel: "Find a quake or a volcano",
    groupFilter: true,
  },
});
```

### React on MapLibre

`packages/maplace/examples/earthquakes/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. -->
<style>
  #earthquakes-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #earthquakes-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-maplibre-react-root .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-maplibre-react-root .map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-maplibre-react-root .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

/** The quakes' group is drawn as heat, each quake weighing its magnitude; the volcanoes, pins. */
const HEATMAP = { groups: ["Quakes"] };
const FIRST_VIEW = { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 } as const;

async function fetched(url: string): Promise<Location[]> {
  return (await fetch(url)).json();
}

function Earthquakes() {
  const [locations, setLocations] = useState<readonly Location[]>([]);
  useEffect(() => {
    Promise.all([
      fetched("/examples/data/earthquakes.json"),
      fetched("/examples/data/volcanoes.json"),
    ]).then(([quakes, volcanoes]) => setLocations([...quakes, ...volcanoes]));
  }, []);
  return (
    <MaplaceProvider locations={locations} heatmap={HEATMAP} view={FIRST_VIEW}>
      <div className="map-and-list">
        <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
        <LocationList search searchLabel="Find a quake or a volcano" groupFilter />
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("earthquakes-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <Earthquakes />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/earthquakes/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>
<style>
  #earthquakes-react-root .map-and-list { display: flex; height: 24rem; }
  #earthquakes-react-root .map { flex: 1 1 auto; min-width: 0; }
  #earthquakes-react-root .maplace-list { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, its half staying that size as the quakes narrow. */
  @media (width < 40rem) {
    #earthquakes-react-root .map-and-list { flex-direction: column; height: 36rem; }
    #earthquakes-react-root .maplace-list { flex: 0 0 50%; max-height: 50%; }
  }
</style>
<div id="earthquakes-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

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

/** The quakes' group is drawn as heat, each quake weighing its magnitude; the volcanoes, pins. */
const HEATMAP = { groups: ["Quakes"] };
const FIRST_VIEW = { kind: "center", center: { lat: 20, lng: 160 }, zoom: 2 } as const;

async function fetched(url: string): Promise<Location[]> {
  return (await fetch(url)).json();
}

function Earthquakes() {
  const [locations, setLocations] = useState<readonly Location[]>([]);
  useEffect(() => {
    Promise.all([
      fetched("/examples/data/earthquakes.json"),
      fetched("/examples/data/volcanoes.json"),
    ]).then(([quakes, volcanoes]) => setLocations([...quakes, ...volcanoes]));
  }, []);
  return (
    <MaplaceProvider locations={locations} heatmap={HEATMAP} view={FIRST_VIEW}>
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
        <LocationList search searchLabel="Find a quake or a volcano" groupFilter />
      </div>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("earthquakes-react-root") as HTMLElement).render(
  <StrictMode>
    <Earthquakes />
  </StrictMode>,
);
```

## Driving route

A drive through your own places, with directions by leg: Google computes it live; on MapLibre it's one stored route, as your own routing service would answer.

A drive through your own places, passing through one without stopping, with its directions leg by leg below the map. On Google, Google computes it live, for any stops you give it. MapLibre has no routing of its own: the page's `computeRoute` answers, and here it replays one route stored beside the example, Milan to Munich (computed once by OSRM; roads © OpenStreetMap contributors, ODbL), so on MapLibre this route is fixed. In your page, `computeRoute` asks a routing service, and any stops route as on Google.

- **Try it**: pick a place in the list, and the route stays. Switch to MapLibre: the same drive, replayed from the stored route. Read the directions below the map, each leg under a heading with its distance, and the total under them.
- **HTML**: the `route` property, `{ stops, via, travelMode }`, naming your locations by id ([Properties and methods](/element/#properties-and-methods)), and a `maplace-routechange` listener writing the directions from the result's legs and steps ([Events](/element/#events)).
- **Script** and **Bundler**: `route` in the map's options, or [`setRoute`](/store/#methods), and a `routeChange` listener ([Routes](/store/#routes)); [Routes on Google](/google/#routes) has its limits.
- **React**: the `route` prop and `onRouteChange` on `<MaplaceProvider>` ([`<MaplaceProvider>`](/react/#maplaceprovider), [Event props](/react/#event-props)).
- **On MapLibre**: the same, plus `computeRoute`: the element's property, `createMapLibreMap`'s option or `createMapLibreAdapter`'s; [Routes on MapLibre](/maplibre/#routes) shows one asking a live OSRM server.


### HTML on MapLibre

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- One route through your own locations, passing through Zurich, with directions from its steps. MapLibre has no routing of its own: the page's computeRoute answers, here from a route stored beside the example (a live service such as OSRM in your page). -->
<style>
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-maplibre-directions:empty { display: none; }
  #route-maplibre-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-maplibre-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-maplibre-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<maplace-map id="route-maplibre-map" list>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="zurich" lat="47.3769" lng="8.5417" title="Zurich"></maplace-location>
  <maplace-location location-id="paris" lat="48.8566" lng="2.3522" title="Paris"></maplace-location>
  <maplace-location location-id="munich" lat="48.1351" lng="11.582" title="Munich"></maplace-location>
</maplace-map>
<div id="route-maplibre-directions"></div>
<p>Total: <output id="route-maplibre-distance"></output></p>
<script>
  const routeMaplibreMap = document.getElementById('route-maplibre-map');

  /**
   * Answers as a routing service would, from the route stored beside the example (its stops' ids,
   * legs and path); any other journey is refused.
   */
  async function routeMaplibreStored({ stops, signal }) {
    const response = await fetch('/examples/data/route-milan-munich.json', { signal });
    if (!response.ok) throw new Error(`The stored route: ${response.status}`);
    const route = await response.json();
    if (stops.map(({ id }) => id).join() !== route.stops.join()) {
      throw new Error('This example has one stored route: Milan to Munich');
    }
    return route;
  }

  routeMaplibreMap.computeRoute = routeMaplibreStored;
  routeMaplibreMap.route = { stops: ['milan', 'zurich', 'paris', 'munich'], via: ['zurich'], travelMode: 'driving' };

  function routeMaplibreKm(meters) {
    return `${Math.round(meters / 1000)} km`;
  }

  function routeMaplibreTitleOf(id) {
    return routeMaplibreMap.locations.find((location) => location.id === id)?.title ?? id;
  }

  /** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
  function routeMaplibreLegDirections(leg) {
    const heading = document.createElement('h3');
    heading.textContent = `${routeMaplibreTitleOf(leg.from)} → ${routeMaplibreTitleOf(leg.to)}, ${routeMaplibreKm(leg.distanceMeters)}`;
    const steps = document.createElement('ol');
    for (const step of leg.steps) {
      const item = document.createElement('li');
      item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
      steps.append(item);
    }
    return [heading, steps];
  }

  routeMaplibreMap.addEventListener('maplace-routechange', (event) => {
    const result = event.detail.result;
    document.getElementById('route-maplibre-directions').replaceChildren(...(result?.legs.flatMap(routeMaplibreLegDirections) ?? []));
    document.getElementById('route-maplibre-distance').textContent = result ? routeMaplibreKm(result.distanceMeters) : '';
  });
</script>
```

### HTML on Google

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

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- One route through your own locations, passing through Zurich, with directions from its steps. -->
<style>
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-directions:empty { display: none; }
  #route-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<maplace-map id="route-map" api-key="YOUR_KEY" list>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="zurich" lat="47.3769" lng="8.5417" title="Zurich"></maplace-location>
  <maplace-location location-id="paris" lat="48.8566" lng="2.3522" title="Paris"></maplace-location>
  <maplace-location location-id="munich" lat="48.1351" lng="11.582" title="Munich"></maplace-location>
</maplace-map>
<div id="route-directions"></div>
<p>Total: <output id="route-distance"></output></p>
<script>
  const routeMap = document.getElementById('route-map');
  routeMap.route = { stops: ['milan', 'zurich', 'paris', 'munich'], via: ['zurich'], travelMode: 'driving' };

  function routeKm(meters) {
    return `${Math.round(meters / 1000)} km`;
  }

  function routeTitleOf(id) {
    return routeMap.locations.find((location) => location.id === id)?.title ?? id;
  }

  /** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
  function routeLegDirections(leg) {
    const heading = document.createElement('h3');
    heading.textContent = `${routeTitleOf(leg.from)} → ${routeTitleOf(leg.to)}, ${routeKm(leg.distanceMeters)}`;
    const steps = document.createElement('ol');
    for (const step of leg.steps) {
      const item = document.createElement('li');
      item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
      steps.append(item);
    }
    return [heading, steps];
  }

  routeMap.addEventListener('maplace-routechange', (event) => {
    const result = event.detail.result;
    document.getElementById('route-directions').replaceChildren(...(result?.legs.flatMap(routeLegDirections) ?? []));
    document.getElementById('route-distance').textContent = result ? routeKm(result.distanceMeters) : '';
  });
</script>
```

### Script on MapLibre

`packages/maplace/examples/route/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, its list, the directions and the total mount on, and the map made with Maplace, routing through the page's computeRoute: here a route stored beside the example. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #route-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #route-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #route-maplibre-script-list { display: contents; }
  #route-maplibre-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-maplibre-script-map-and-list { flex-direction: column; }
    #route-maplibre-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-maplibre-script-directions:empty { display: none; }
  #route-maplibre-script-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-maplibre-script-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-maplibre-script-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-maplibre-script-map-and-list">
  <div id="route-maplibre-script-map"></div>
  <div id="route-maplibre-script-list"></div>
</div>
<div id="route-maplibre-script-directions"></div>
<p>Total: <output id="route-maplibre-script-distance"></output></p>
<script type="module">
  const locations = [
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
    { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
    { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
  ];
  /**
   * Answers as a routing service would, from the route stored beside the example (its stops' ids,
   * legs and path); any other journey is refused.
   */
  async function storedRoute({ stops, signal }) {
    const response = await fetch("/examples/data/route-milan-munich.json", { signal });
    if (!response.ok) throw new Error(`The stored route: ${response.status}`);
    const route = await response.json();
    if (stops.map(({ id }) => id).join() !== route.stops.join()) {
      throw new Error("This example has one stored route: Milan to Munich");
    }
    return route;
  }

  const maplace = Maplace.createMapLibreMap("#route-maplibre-script-map", {
    locations,
    computeRoute: storedRoute,
    list: { container: "#route-maplibre-script-list" },
  });
  maplace.setRoute({
    stops: ["milan", "zurich", "paris", "munich"],
    via: ["zurich"],
    travelMode: "driving",
  });

  const km = (meters) => `${Math.round(meters / 1000)} km`;
  const titleOf = (id) => locations.find((location) => location.id === id)?.title ?? id;
  const directions = document.querySelector("#route-maplibre-script-directions");
  const distance = document.querySelector("#route-maplibre-script-distance");
  maplace.on("routeChange", ({ result }) => {
    directions?.replaceChildren(...(result?.legs.flatMap(legDirections) ?? []));
    if (distance) distance.textContent = result ? km(result.distanceMeters) : "";
  });

  /**
   * A leg's steps, headed by where it runs and how far; a step without words shows its distance.
   */
  function legDirections(leg) {
    const heading = document.createElement("h3");
    heading.textContent = `${titleOf(leg.from)} → ${titleOf(leg.to)}, ${km(leg.distanceMeters)}`;
    const steps = document.createElement("ol");
    for (const step of leg.steps) {
      const item = document.createElement("li");
      item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
      steps.append(item);
    }
    return [heading, steps];
  }
</script>
```

### Script on Google

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

```html
<!doctype html>
<!-- A page of your own script: the CDN script, what the map, its list, the directions and the total 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>
<style>
  #route-script-map-and-list { display: flex; height: 24rem; }
  #route-script-map { flex: 1 1 auto; min-width: 0; }
  #route-script-list { display: contents; }
  #route-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-script-map-and-list { flex-direction: column; }
    #route-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-script-directions:empty { display: none; }
  #route-script-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-script-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-script-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-script-map-and-list">
  <div id="route-script-map"></div>
  <div id="route-script-list"></div>
</div>
<div id="route-script-directions"></div>
<p>Total: <output id="route-script-distance"></output></p>
<script type="module">
  const locations = [
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
    { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
    { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
  ];
  const maplace = Maplace.createGoogleMap("#route-script-map", {
    apiKey: "YOUR_KEY",
    locations,
    list: { container: "#route-script-list" },
  });
  maplace.setRoute({
    stops: ["milan", "zurich", "paris", "munich"],
    via: ["zurich"],
    travelMode: "driving",
  });

  const km = (meters) => `${Math.round(meters / 1000)} km`;
  const titleOf = (id) => locations.find((location) => location.id === id)?.title ?? id;
  const directions = document.querySelector("#route-script-directions");
  const distance = document.querySelector("#route-script-distance");
  maplace.on("routeChange", ({ result }) => {
    directions?.replaceChildren(...(result?.legs.flatMap(legDirections) ?? []));
    if (distance) distance.textContent = result ? km(result.distanceMeters) : "";
  });

  /**
   * A leg's steps, headed by where it runs and how far; a step without words shows its distance.
   */
  function legDirections(leg) {
    const heading = document.createElement("h3");
    heading.textContent = `${titleOf(leg.from)} → ${titleOf(leg.to)}, ${km(leg.distanceMeters)}`;
    const steps = document.createElement("ol");
    for (const step of leg.steps) {
      const item = document.createElement("li");
      item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
      steps.append(item);
    }
    return [heading, steps];
  }
</script>
```

### Bundler on MapLibre

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

```html
<!doctype html>
<!-- The page vanilla.ts runs on: what the map, its list, the directions and the total mount on, and the module, which brings maplibre-gl and its stylesheet. -->
<style>
  #route-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #route-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #route-maplibre-vanilla-list { display: contents; }
  #route-maplibre-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-maplibre-vanilla-map-and-list { flex-direction: column; }
    #route-maplibre-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-maplibre-vanilla-directions:empty { display: none; }
  #route-maplibre-vanilla-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-maplibre-vanilla-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-maplibre-vanilla-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-maplibre-vanilla-map-and-list">
  <div id="route-maplibre-vanilla-map"></div>
  <div id="route-maplibre-vanilla-list"></div>
</div>
<div id="route-maplibre-vanilla-directions"></div>
<p>Total: <output id="route-maplibre-vanilla-distance"></output></p>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const locations: Location[] = [
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
  { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
  { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
];

/**
 * Answers as a routing service would, from the route stored beside the example (its stops' ids,
 * legs and path); any other journey is refused.
 */
const storedRoute: RouteComputer = async ({ stops, signal }) => {
  const response = await fetch("/examples/data/route-milan-munich.json", { signal });
  if (!response.ok) throw new Error(`The stored route: ${response.status}`);
  const route: RouteAnswer & { stops: string[] } = await response.json();
  if (stops.map(({ id }) => id).join() !== route.stops.join()) {
    throw new Error("This example has one stored route: Milan to Munich");
  }
  return route;
};

// MapLibre has no routing of its own: the page's computeRoute answers (a live service, such as
// OSRM, in your page).
const maplace = createMapLibreMap("#route-maplibre-vanilla-map", {
  locations,
  computeRoute: storedRoute,
  list: { container: "#route-maplibre-vanilla-list" },
});
maplace.setRoute({
  stops: ["milan", "zurich", "paris", "munich"],
  via: ["zurich"],
  travelMode: "driving",
});

const km = (meters: number) => `${Math.round(meters / 1000)} km`;
const titleOf = (id: string) => locations.find((location) => location.id === id)?.title ?? id;
const directions = document.querySelector("#route-maplibre-vanilla-directions");
const distance = document.querySelector("#route-maplibre-vanilla-distance");
maplace.on("routeChange", ({ result }) => {
  directions?.replaceChildren(...(result?.legs.flatMap(legDirections) ?? []));
  if (distance) distance.textContent = result ? km(result.distanceMeters) : "";
});

/** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
function legDirections(leg: RouteLeg): HTMLElement[] {
  const heading = document.createElement("h3");
  heading.textContent = `${titleOf(leg.from)} → ${titleOf(leg.to)}, ${km(leg.distanceMeters)}`;
  const steps = document.createElement("ol");
  for (const step of leg.steps) {
    const item = document.createElement("li");
    item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
    steps.append(item);
  }
  return [heading, steps];
}
```

### Bundler on Google

`packages/maplace/examples/route/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>
<style>
  #route-vanilla-map-and-list { display: flex; height: 24rem; }
  #route-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #route-vanilla-list { display: contents; }
  #route-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-vanilla-map-and-list { flex-direction: column; }
    #route-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-vanilla-directions:empty { display: none; }
  #route-vanilla-directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-vanilla-directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-vanilla-directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-vanilla-map-and-list">
  <div id="route-vanilla-map"></div>
  <div id="route-vanilla-list"></div>
</div>
<div id="route-vanilla-directions"></div>
<p>Total: <output id="route-vanilla-distance"></output></p>
<script type="module" src="./vanilla.ts"></script>
```

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

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

const locations: Location[] = [
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
  { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
  { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
];
const maplace = createGoogleMap("#route-vanilla-map", {
  locations,
  list: { container: "#route-vanilla-list" },
});
maplace.setRoute({
  stops: ["milan", "zurich", "paris", "munich"],
  via: ["zurich"],
  travelMode: "driving",
});

const km = (meters: number) => `${Math.round(meters / 1000)} km`;
const titleOf = (id: string) => locations.find((location) => location.id === id)?.title ?? id;
const directions = document.querySelector("#route-vanilla-directions");
const distance = document.querySelector("#route-vanilla-distance");
maplace.on("routeChange", ({ result }) => {
  directions?.replaceChildren(...(result?.legs.flatMap(legDirections) ?? []));
  if (distance) distance.textContent = result ? km(result.distanceMeters) : "";
});

/** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
function legDirections(leg: RouteLeg): HTMLElement[] {
  const heading = document.createElement("h3");
  heading.textContent = `${titleOf(leg.from)} → ${titleOf(leg.to)}, ${km(leg.distanceMeters)}`;
  const steps = document.createElement("ol");
  for (const step of leg.steps) {
    const item = document.createElement("li");
    item.textContent = step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`;
    steps.append(item);
  }
  return [heading, steps];
}
```

### React on MapLibre

`packages/maplace/examples/route/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. -->
<style>
  #route-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #route-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #route-maplibre-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-maplibre-react-root .map-and-list { flex-direction: column; }
    #route-maplibre-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-maplibre-react-root .directions:empty { display: none; }
  #route-maplibre-react-root .directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-maplibre-react-root .directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-maplibre-react-root .directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

```tsx
import "maplibre-gl/dist/maplibre-gl.css";
import type {
  Location,
  Route as MaplaceRoute,
  RouteAnswer,
  RouteComputer,
  RouteLeg,
  RouteResult,
  RouteStep,
} from "@maplacejs/maplace";
import { createMapLibreAdapter } from "@maplacejs/maplace/maplibre";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";

const cities: Location[] = [
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
  { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
  { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
];
const ROUTE: MaplaceRoute = {
  stops: ["milan", "zurich", "paris", "munich"],
  via: ["zurich"],
  travelMode: "driving",
};

/**
 * Answers as a routing service would, from the route stored beside the example (its stops' ids,
 * legs and path); any other journey is refused.
 */
const storedRoute: RouteComputer = async ({ stops, signal }) => {
  const response = await fetch("/examples/data/route-milan-munich.json", { signal });
  if (!response.ok) throw new Error(`The stored route: ${response.status}`);
  const route: RouteAnswer & { stops: string[] } = await response.json();
  if (stops.map(({ id }) => id).join() !== route.stops.join()) {
    throw new Error("This example has one stored route: Milan to Munich");
  }
  return route;
};

// MapLibre has no routing of its own: the page's computeRoute answers (a live service, such as
// OSRM, in your page).
const createAdapter = () => createMapLibreAdapter({ computeRoute: storedRoute });

const km = (meters: number) => `${Math.round(meters / 1000)} km`;
const titleOf = (id: string) => cities.find((city) => city.id === id)?.title ?? id;
const keyOf = (step: RouteStep) =>
  `${step.distanceMeters}:${step.durationSeconds}:${step.instruction ?? ""}`;

/** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
function LegDirections({ leg }: { readonly leg: RouteLeg }) {
  return (
    <>
      <h3>
        {titleOf(leg.from)} → {titleOf(leg.to)}, {km(leg.distanceMeters)}
      </h3>
      <ol>
        {leg.steps.map((step) => (
          <li key={keyOf(step)}>
            {step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`}
          </li>
        ))}
      </ol>
    </>
  );
}

function Route() {
  const [result, setResult] = useState<RouteResult>();
  return (
    <MaplaceProvider
      locations={cities}
      route={ROUTE}
      onRouteChange={({ result }) => setResult(result)}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createAdapter} className="map" />
        <LocationList />
      </div>
      <div className="directions">
        {result?.legs.map((leg) => (
          <LegDirections key={`${leg.from}-${leg.to}`} leg={leg} />
        ))}
      </div>
      <p>
        Total: <output>{result ? km(result.distanceMeters) : ""}</output>
      </p>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("route-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <Route />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/route/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>
<style>
  #route-react-root .map-and-list { display: flex; height: 24rem; }
  #route-react-root .map { flex: 1 1 auto; min-width: 0; }
  #route-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #route-react-root .map-and-list { flex-direction: column; }
    #route-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
  /* The directions in a panel of their own, below the map: its legs' headings stay in view as
     their steps scroll, and a shade at the bottom shows there is more, gone at the end. */
  #route-react-root .directions:empty { display: none; }
  #route-react-root .directions {
    margin-top: 1rem; max-height: 18rem; overflow: auto; padding: 0 1.25rem 0.5rem;
    border: 1px solid color-mix(in srgb, currentColor 25%, transparent); border-radius: 0.5rem;
    background:
      linear-gradient(transparent, Canvas 70%) bottom / 100% 1.5rem no-repeat local,
      linear-gradient(transparent, color-mix(in srgb, currentColor 8%, transparent)) bottom / 100% 0.75rem no-repeat,
      Canvas;
  }
  #route-react-root .directions h3 {
    position: sticky; top: 0; margin: 0; padding: 0.75rem 0 0.5rem; background: Canvas;
    border-bottom: 1px solid color-mix(in srgb, currentColor 15%, transparent);
  }
  #route-react-root .directions ol { margin: 0.5rem 0 1rem; line-height: 1.6; }
</style>
<div id="route-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

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

```tsx
import type {
  Location,
  Route as MaplaceRoute,
  RouteLeg,
  RouteResult,
  RouteStep,
} from "@maplacejs/maplace";
import { createGoogleAdapter } from "@maplacejs/maplace/google";
import { LocationList, MaplaceMap, MaplaceProvider } from "@maplacejs/maplace/react";
import { StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";

const cities: Location[] = [
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "zurich", lat: 47.3769, lng: 8.5417, title: "Zurich" },
  { id: "paris", lat: 48.8566, lng: 2.3522, title: "Paris" },
  { id: "munich", lat: 48.1351, lng: 11.582, title: "Munich" },
];
const ROUTE: MaplaceRoute = {
  stops: ["milan", "zurich", "paris", "munich"],
  via: ["zurich"],
  travelMode: "driving",
};

const km = (meters: number) => `${Math.round(meters / 1000)} km`;
const titleOf = (id: string) => cities.find((city) => city.id === id)?.title ?? id;
const keyOf = (step: RouteStep) =>
  `${step.distanceMeters}:${step.durationSeconds}:${step.instruction ?? ""}`;

/** A leg's steps, headed by where it runs and how far; a step without words shows its distance. */
function LegDirections({ leg }: { readonly leg: RouteLeg }) {
  return (
    <>
      <h3>
        {titleOf(leg.from)} → {titleOf(leg.to)}, {km(leg.distanceMeters)}
      </h3>
      <ol>
        {leg.steps.map((step) => (
          <li key={keyOf(step)}>
            {step.instruction ?? `${(step.distanceMeters / 1000).toFixed(1)} km`}
          </li>
        ))}
      </ol>
    </>
  );
}

function Route() {
  const [result, setResult] = useState<RouteResult>();
  return (
    <MaplaceProvider
      locations={cities}
      route={ROUTE}
      onRouteChange={({ result }) => setResult(result)}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
        <LocationList />
      </div>
      <div className="directions">
        {result?.legs.map((leg) => (
          <LegDirections key={`${leg.from}-${leg.to}`} leg={leg} />
        ))}
      </div>
      <p>
        Total: <output>{result ? km(result.distanceMeters) : ""}</output>
      </p>
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("route-react-root") as HTMLElement).render(
  <StrictMode>
    <Route />
  </StrictMode>,
);
```

## Load on demand

A panel in the map's place: nothing draws until the visitor presses its button.

The map stays idle in its place, its tiles and its provider's requests waiting, until the visitor presses a button: for a heavy map low on a page, or to ask first.

- **Try it**: press **Load map** and the map draws. Every version shows the same panel, a line naming whom the map loads from and the button: the HTML version's is the element's own, the others write their own with its look. On this site the map's script is loaded once you accept maps, so what waits for the press is the map and its tiles.
- **HTML**: `hold` on `<maplace-map>` shows the panel; its button calls `release()`, which a script of yours can call too. `load-label` and `load-from-label` set its words. For a map that waits until it scrolls into view instead, `loading="lazy"` ([Load states](/element/#load-states)).
- **Script** and **Bundler**: a panel of yours, a line naming whom the map loads from and a button, with `createGoogleMap` or `createMapLibreMap` in the button's click listener, so nothing is created until then ([Creating a store](/store/#creating-a-store)). The panel goes with the press, focus moved to the map's box first, so a keyboard reader isn't sent back to the top of the page.
- **React**: state for whether it was pressed, rendering the panel or the `<MaplaceProvider>` and `<MaplaceMap>`, the press moving the focus ([`<MaplaceMap>`](/react/#maplacemap)).


### HTML on MapLibre

`packages/maplace/examples/load-on-demand/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- hold keeps the map idle, asking its provider for nothing, until the reader presses its Load map button. -->
<maplace-map id="load-on-demand-maplibre-map" hold>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples"></maplace-location>
</maplace-map>
```

### HTML on Google

`packages/maplace/examples/load-on-demand/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- hold keeps the map idle, asking its provider for nothing, until the reader presses its Load map button. -->
<maplace-map id="load-on-demand-map" api-key="YOUR_KEY" hold>
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples"></maplace-location>
</maplace-map>
```

### Script on MapLibre

`packages/maplace/examples/load-on-demand/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. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<style>
  #load-on-demand-maplibre-script-map { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-maplibre-script-map .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-maplibre-script-map .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
</style>
<div id="load-on-demand-maplibre-script-map"></div>
<script type="module">
  const box = document.getElementById("load-on-demand-maplibre-script-map");
  const locations = [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  ];

  const panel = document.createElement("div");
  panel.className = "load-panel";
  const line = document.createElement("span");
  line.textContent = "Loads from OpenFreeMap";
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = "Load map";
  button.addEventListener("click", () => {
    // The panel goes as it's pressed: focus stays here, not at the top of the page.
    box.tabIndex = -1;
    box.focus({ preventScroll: true });
    panel.remove();
    Maplace.createMapLibreMap(box, { locations });
  });
  panel.append(line, button);
  box.append(panel);
</script>
```

### Script on Google

`packages/maplace/examples/load-on-demand/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. -->
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<style>
  #load-on-demand-script-map { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-script-map .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-script-map .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
</style>
<div id="load-on-demand-script-map"></div>
<script type="module">
  const box = document.getElementById("load-on-demand-script-map");
  const locations = [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  ];

  const panel = document.createElement("div");
  panel.className = "load-panel";
  const line = document.createElement("span");
  line.textContent = "Loads from Google";
  const button = document.createElement("button");
  button.type = "button";
  button.textContent = "Load map";
  button.addEventListener("click", () => {
    // The panel goes as it's pressed: focus stays here, not at the top of the page.
    box.tabIndex = -1;
    box.focus({ preventScroll: true });
    panel.remove();
    Maplace.createGoogleMap(box, { apiKey: "YOUR_KEY", locations });
  });
  panel.append(line, button);
  box.append(panel);
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/load-on-demand/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. -->
<style>
  #load-on-demand-maplibre-vanilla-map { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-maplibre-vanilla-map .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-maplibre-vanilla-map .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
</style>
<div id="load-on-demand-maplibre-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/load-on-demand/maplibre/vanilla.ts`

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

const box = document.getElementById("load-on-demand-maplibre-vanilla-map") as HTMLElement;
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
];

const panel = document.createElement("div");
panel.className = "load-panel";
const line = document.createElement("span");
line.textContent = "Loads from OpenFreeMap";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Load map";
button.addEventListener("click", () => {
  // The panel goes as it's pressed: focus stays here, not at the top of the page.
  box.tabIndex = -1;
  box.focus({ preventScroll: true });
  panel.remove();
  createMapLibreMap(box, { locations });
});
panel.append(line, button);
box.append(panel);
```

### Bundler on Google

`packages/maplace/examples/load-on-demand/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>
<style>
  #load-on-demand-vanilla-map { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-vanilla-map .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-vanilla-map .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
</style>
<div id="load-on-demand-vanilla-map"></div>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/load-on-demand/vanilla.ts`

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

const box = document.getElementById("load-on-demand-vanilla-map") as HTMLElement;
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
];

const panel = document.createElement("div");
panel.className = "load-panel";
const line = document.createElement("span");
line.textContent = "Loads from Google";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Load map";
button.addEventListener("click", () => {
  // The panel goes as it's pressed: focus stays here, not at the top of the page.
  box.tabIndex = -1;
  box.focus({ preventScroll: true });
  panel.remove();
  createGoogleMap(box, { locations });
});
panel.append(line, button);
box.append(panel);
```

### React on MapLibre

`packages/maplace/examples/load-on-demand/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. -->
<style>
  #load-on-demand-maplibre-react-root .box { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-maplibre-react-root .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-maplibre-react-root .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
  #load-on-demand-maplibre-react-root .map { height: 100%; }
</style>
<div id="load-on-demand-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/load-on-demand/maplibre/react.tsx`

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

const cities: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
];

function LoadOnDemand() {
  const [loaded, setLoaded] = useState(false);
  const box = useRef<HTMLDivElement>(null);
  const load = () => {
    // The panel goes as it's pressed: focus stays here, not at the top of the page.
    box.current?.focus({ preventScroll: true });
    setLoaded(true);
  };
  return (
    <div className="box" ref={box} tabIndex={-1}>
      {loaded ? (
        <MaplaceProvider locations={cities}>
          <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
        </MaplaceProvider>
      ) : (
        <div className="load-panel">
          <span>Loads from OpenFreeMap</span>
          <button type="button" onClick={load}>
            Load map
          </button>
        </div>
      )}
    </div>
  );
}

createRoot(document.getElementById("load-on-demand-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <LoadOnDemand />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/load-on-demand/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>
<style>
  #load-on-demand-react-root .box { height: 24rem; }
  /* The panel the map waits behind: the look <maplace-map hold> gives its own. */
  #load-on-demand-react-root .load-panel { display: grid; place-content: center; justify-items: center; gap: 0.75rem; height: 100%; padding-inline: 1rem; text-align: center; background: #8881; }
  #load-on-demand-react-root .load-panel > button { padding: 0.5rem 1rem; border: 1px solid; border-radius: 0.375rem; background: none; color: inherit; font: inherit; font-weight: 600; cursor: pointer; }
  #load-on-demand-react-root .map { height: 100%; }
</style>
<div id="load-on-demand-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/load-on-demand/react.tsx`

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

const cities: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
];

function LoadOnDemand() {
  const [loaded, setLoaded] = useState(false);
  const box = useRef<HTMLDivElement>(null);
  const load = () => {
    // The panel goes as it's pressed: focus stays here, not at the top of the page.
    box.current?.focus({ preventScroll: true });
    setLoaded(true);
  };
  return (
    <div className="box" ref={box} tabIndex={-1}>
      {loaded ? (
        <MaplaceProvider locations={cities}>
          <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
        </MaplaceProvider>
      ) : (
        <div className="load-panel">
          <span>Loads from Google</span>
          <button type="button" onClick={load}>
            Load map
          </button>
        </div>
      )}
    </div>
  );
}

createRoot(document.getElementById("load-on-demand-react-root") as HTMLElement).render(
  <StrictMode>
    <LoadOnDemand />
  </StrictMode>,
);
```

## Link to a place

A link to the place picked, shown under the map, that opens the map on it.

The page's address names the place picked, and the line under the map gives its link: following it opens the map on that place, and the back button steps through what was picked. "View all", the list's first entry, takes it out again.

- **Try it**: on the HTML version, pick Milan: the line under the map gives its link, `?place=milan` on Google and `?place-maplibre=milan` on MapLibre. Follow it, and the page opens again on Milan; press back to step through. This site opens on the HTML version, so only that version's link works here: each version has its own parameter, as a parameter belongs to one map. On your own page, with one version, its link just works.
- **HTML**: `url-state="place"` on `<maplace-map>`, `url-state="place-maplibre"` on MapLibre, does all of it, a place no location has being ignored ([URL state](/element/#url-state)); `fit-all` and `fit-all-label` add the first entry ([Map attributes](/element/#map-attributes)). The line under the map is the page's own script, on `maplace-selectionchange`: a link needs only the parameter, and the map's id as its hash so a long page lands on it.
- **Script** and **Bundler**: by hand, in a few lines: `selectedId` from the address, checked against your locations as an unknown id throws ([Options](/store/#options)); a `selectionChange` listener calling `history.pushState`; and a `popstate` listener calling [`select`](/store/#methods). `list: { fitAll: true, fitAllLabel }` adds the first entry ([List view options](/store/#list-view-options)), and the same listener writes the line under the map.
- **React**: `defaultSelectedId` and `onSelectionChange` on `<MaplaceProvider>` ([Controlled selection](/react/#controlled-selection)), and small components through [`useMaplace()`](/react/#usemaplace): one selecting on `popstate`, one writing the line under the map.


### HTML on MapLibre

`packages/maplace/examples/link-to-place/maplibre/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element-maplibre.iife.js"></script>
<!-- The address says which place is selected: a link opens on it, and back steps through what was picked; "View all" takes it out. The line under the map gives the link to what is picked. -->
<maplace-map id="link-to-place-maplibre-map" list fit-all fit-all-label="View all" url-state="place-maplibre">
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples"></maplace-location>
  <maplace-location location-id="turin" lat="45.0703" lng="7.6869" title="Turin"></maplace-location>
</maplace-map>
<p id="link-to-place-maplibre-link"></p>
<script>
  const linkToPlaceMapLibreMap = document.getElementById('link-to-place-maplibre-map');

  /** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
  function linkToPlaceMapLibreShowLink(id) {
    const line = document.getElementById('link-to-place-maplibre-link');
    if (id === undefined) {
      line.textContent = 'Pick a place for a link to it.';
      return;
    }
    const address = new URL(location.href);
    address.searchParams.set('place-maplibre', id);
    address.hash = 'link-to-place-maplibre-map';
    const link = document.createElement('a');
    link.href = address.href;
    link.textContent = address.search;
    line.replaceChildren('Link to this place: ', link);
  }

  linkToPlaceMapLibreShowLink(linkToPlaceMapLibreMap.maplace.getSnapshot().selectedId);
  linkToPlaceMapLibreMap.addEventListener('maplace-selectionchange', (event) => linkToPlaceMapLibreShowLink(event.detail.id));
</script>
```

### HTML on Google

`packages/maplace/examples/link-to-place/page.html`

```html
<!doctype html>
<script src="https://cdn.jsdelivr.net/npm/@maplacejs/maplace@1/dist/maplace-element.iife.js"></script>
<!-- The address says which place is selected: a link opens on it, and back steps through what was picked; "View all" takes it out. The line under the map gives the link to what is picked. -->
<maplace-map id="link-to-place-map" api-key="YOUR_KEY" list fit-all fit-all-label="View all" url-state="place">
  <maplace-location location-id="rome" lat="41.9028" lng="12.4964" title="Rome"></maplace-location>
  <maplace-location location-id="milan" lat="45.4642" lng="9.19" title="Milan"></maplace-location>
  <maplace-location location-id="naples" lat="40.8518" lng="14.2681" title="Naples"></maplace-location>
  <maplace-location location-id="turin" lat="45.0703" lng="7.6869" title="Turin"></maplace-location>
</maplace-map>
<p id="link-to-place-link"></p>
<script>
  const linkToPlaceMap = document.getElementById('link-to-place-map');

  /** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
  function linkToPlaceShowLink(id) {
    const line = document.getElementById('link-to-place-link');
    if (id === undefined) {
      line.textContent = 'Pick a place for a link to it.';
      return;
    }
    const address = new URL(location.href);
    address.searchParams.set('place', id);
    address.hash = 'link-to-place-map';
    const link = document.createElement('a');
    link.href = address.href;
    link.textContent = address.search;
    line.replaceChildren('Link to this place: ', link);
  }

  linkToPlaceShowLink(linkToPlaceMap.maplace.getSnapshot().selectedId);
  linkToPlaceMap.addEventListener('maplace-selectionchange', (event) => linkToPlaceShowLink(event.detail.id));
</script>
```

### Script on MapLibre

`packages/maplace/examples/link-to-place/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>
<style>
  #link-to-place-maplibre-script-map-and-list { display: flex; height: 24rem; }
  #link-to-place-maplibre-script-map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-maplibre-script-list { display: contents; }
  #link-to-place-maplibre-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-maplibre-script-map-and-list { flex-direction: column; }
    #link-to-place-maplibre-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-maplibre-script-map-and-list">
  <div id="link-to-place-maplibre-script-map"></div>
  <div id="link-to-place-maplibre-script-list"></div>
</div>
<p id="link-to-place-maplibre-script-link"></p>
<script type="module">
  const PLACE = "place-maplibre-script";
  const locations = [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
    { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
  ];

  /** The place the address names, if there is one: a link can name anything. */
  function placeInAddress() {
    const id = new URLSearchParams(location.search).get(PLACE);
    return locations.find((place) => place.id === id)?.id;
  }

  /** A new history entry for a place picked, unless the address says so already. */
  function writeAddress({ id }) {
    if (id === placeInAddress()) return;
    const address = new URL(location.href);
    if (id === undefined) address.searchParams.delete(PLACE);
    else address.searchParams.set(PLACE, id);
    history.pushState(null, "", address);
  }

  /** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
  function showLink(id) {
    const line = document.getElementById("link-to-place-maplibre-script-link");
    if (id === undefined) {
      line.textContent = "Pick a place for a link to it.";
      return;
    }
    const address = new URL(location.href);
    address.searchParams.set(PLACE, id);
    address.hash = "link-to-place-maplibre-script-map";
    const link = document.createElement("a");
    link.href = address.href;
    link.textContent = address.search;
    line.replaceChildren("Link to this place: ", link);
  }

  const maplace = Maplace.createMapLibreMap("#link-to-place-maplibre-script-map", {
    locations,
    selectedId: placeInAddress(),
    list: { container: "#link-to-place-maplibre-script-list", fitAll: true, fitAllLabel: "View all" },
  });
  showLink(maplace.getSnapshot().selectedId);
  maplace.on("selectionChange", (change) => {
    writeAddress(change);
    showLink(change.id);
  });
  // Only on a change: selecting the selected place again would pan back to it.
  addEventListener("popstate", () => {
    const place = placeInAddress();
    if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
  });
</script>
```

### Script on Google

`packages/maplace/examples/link-to-place/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>
<style>
  #link-to-place-script-map-and-list { display: flex; height: 24rem; }
  #link-to-place-script-map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-script-list { display: contents; }
  #link-to-place-script-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-script-map-and-list { flex-direction: column; }
    #link-to-place-script-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-script-map-and-list">
  <div id="link-to-place-script-map"></div>
  <div id="link-to-place-script-list"></div>
</div>
<p id="link-to-place-script-link"></p>
<script type="module">
  const PLACE = "place-script";
  const locations = [
    { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
    { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
    { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
    { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
  ];

  /** The place the address names, if there is one: a link can name anything. */
  function placeInAddress() {
    const id = new URLSearchParams(location.search).get(PLACE);
    return locations.find((place) => place.id === id)?.id;
  }

  /** A new history entry for a place picked, unless the address says so already. */
  function writeAddress({ id }) {
    if (id === placeInAddress()) return;
    const address = new URL(location.href);
    if (id === undefined) address.searchParams.delete(PLACE);
    else address.searchParams.set(PLACE, id);
    history.pushState(null, "", address);
  }

  /** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
  function showLink(id) {
    const line = document.getElementById("link-to-place-script-link");
    if (id === undefined) {
      line.textContent = "Pick a place for a link to it.";
      return;
    }
    const address = new URL(location.href);
    address.searchParams.set(PLACE, id);
    address.hash = "link-to-place-script-map";
    const link = document.createElement("a");
    link.href = address.href;
    link.textContent = address.search;
    line.replaceChildren("Link to this place: ", link);
  }

  const maplace = Maplace.createGoogleMap("#link-to-place-script-map", {
    apiKey: "YOUR_KEY",
    locations,
    selectedId: placeInAddress(),
    list: { container: "#link-to-place-script-list", fitAll: true, fitAllLabel: "View all" },
  });
  showLink(maplace.getSnapshot().selectedId);
  maplace.on("selectionChange", (change) => {
    writeAddress(change);
    showLink(change.id);
  });
  // Only on a change: selecting the selected place again would pan back to it.
  addEventListener("popstate", () => {
    const place = placeInAddress();
    if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
  });
</script>
```

### Bundler on MapLibre

`packages/maplace/examples/link-to-place/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. -->
<style>
  #link-to-place-maplibre-vanilla-map-and-list { display: flex; height: 24rem; }
  #link-to-place-maplibre-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-maplibre-vanilla-list { display: contents; }
  #link-to-place-maplibre-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-maplibre-vanilla-map-and-list { flex-direction: column; }
    #link-to-place-maplibre-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-maplibre-vanilla-map-and-list">
  <div id="link-to-place-maplibre-vanilla-map"></div>
  <div id="link-to-place-maplibre-vanilla-list"></div>
</div>
<p id="link-to-place-maplibre-vanilla-link"></p>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/link-to-place/maplibre/vanilla.ts`

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

const PLACE = "place-maplibre-vanilla";
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
];

/** The place the address names, if there is one: a link can name anything. */
function placeInAddress(): string | undefined {
  const id = new URLSearchParams(location.search).get(PLACE);
  return locations.find((place) => place.id === id)?.id;
}

/** A new history entry for a place picked, unless the address says so already. */
function writeAddress({ id }: { readonly id: string | undefined }): void {
  if (id === placeInAddress()) return;
  const address = new URL(location.href);
  if (id === undefined) address.searchParams.delete(PLACE);
  else address.searchParams.set(PLACE, id);
  history.pushState(null, "", address);
}

/** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
function showLink(id: string | undefined): void {
  const line = document.getElementById("link-to-place-maplibre-vanilla-link") as HTMLElement;
  if (id === undefined) {
    line.textContent = "Pick a place for a link to it.";
    return;
  }
  const address = new URL(location.href);
  address.searchParams.set(PLACE, id);
  address.hash = "link-to-place-maplibre-vanilla-map";
  const link = document.createElement("a");
  link.href = address.href;
  link.textContent = address.search;
  line.replaceChildren("Link to this place: ", link);
}

const maplace = createMapLibreMap("#link-to-place-maplibre-vanilla-map", {
  locations,
  selectedId: placeInAddress(),
  list: {
    container: "#link-to-place-maplibre-vanilla-list",
    fitAll: true,
    fitAllLabel: "View all",
  },
});
showLink(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", (change) => {
  writeAddress(change);
  showLink(change.id);
});
// Only on a change: selecting the selected place again would pan back to it.
addEventListener("popstate", () => {
  const place = placeInAddress();
  if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
});
```

### Bundler on Google

`packages/maplace/examples/link-to-place/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>
<style>
  #link-to-place-vanilla-map-and-list { display: flex; height: 24rem; }
  #link-to-place-vanilla-map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-vanilla-list { display: contents; }
  #link-to-place-vanilla-list [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-vanilla-map-and-list { flex-direction: column; }
    #link-to-place-vanilla-list [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-vanilla-map-and-list">
  <div id="link-to-place-vanilla-map"></div>
  <div id="link-to-place-vanilla-list"></div>
</div>
<p id="link-to-place-vanilla-link"></p>
<script type="module" src="./vanilla.ts"></script>
```

`packages/maplace/examples/link-to-place/vanilla.ts`

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

const PLACE = "place-vanilla";
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
];

/** The place the address names, if there is one: a link can name anything. */
function placeInAddress(): string | undefined {
  const id = new URLSearchParams(location.search).get(PLACE);
  return locations.find((place) => place.id === id)?.id;
}

/** A new history entry for a place picked, unless the address says so already. */
function writeAddress({ id }: { readonly id: string | undefined }): void {
  if (id === placeInAddress()) return;
  const address = new URL(location.href);
  if (id === undefined) address.searchParams.delete(PLACE);
  else address.searchParams.set(PLACE, id);
  history.pushState(null, "", address);
}

/** The line under the map: a link opening on the place `id`, on this map, or a prompt for one. */
function showLink(id: string | undefined): void {
  const line = document.getElementById("link-to-place-vanilla-link") as HTMLElement;
  if (id === undefined) {
    line.textContent = "Pick a place for a link to it.";
    return;
  }
  const address = new URL(location.href);
  address.searchParams.set(PLACE, id);
  address.hash = "link-to-place-vanilla-map";
  const link = document.createElement("a");
  link.href = address.href;
  link.textContent = address.search;
  line.replaceChildren("Link to this place: ", link);
}

const maplace = createGoogleMap("#link-to-place-vanilla-map", {
  locations,
  selectedId: placeInAddress(),
  list: { container: "#link-to-place-vanilla-list", fitAll: true, fitAllLabel: "View all" },
});
showLink(maplace.getSnapshot().selectedId);
maplace.on("selectionChange", (change) => {
  writeAddress(change);
  showLink(change.id);
});
// Only on a change: selecting the selected place again would pan back to it.
addEventListener("popstate", () => {
  const place = placeInAddress();
  if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
});
```

### React on MapLibre

`packages/maplace/examples/link-to-place/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. -->
<style>
  #link-to-place-maplibre-react-root .map-and-list { display: flex; height: 24rem; }
  #link-to-place-maplibre-react-root .map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-maplibre-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-maplibre-react-root .map-and-list { flex-direction: column; }
    #link-to-place-maplibre-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-maplibre-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/link-to-place/maplibre/react.tsx`

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

const PLACE = "place-maplibre-react";
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
];

/** The place the address names, if there is one: a link can name anything. */
function placeInAddress(): string | undefined {
  const id = new URLSearchParams(location.search).get(PLACE);
  return locations.find((place) => place.id === id)?.id;
}

/** A new history entry for a place picked, unless the address says so already. */
function writeAddress({ id }: { readonly id: string | undefined }): void {
  if (id === placeInAddress()) return;
  const address = new URL(location.href);
  if (id === undefined) address.searchParams.delete(PLACE);
  else address.searchParams.set(PLACE, id);
  history.pushState(null, "", address);
}

/** Back and forward select what the address names then. */
function FollowAddress() {
  const maplace = useMaplace();
  useEffect(() => {
    // Only on a change: selecting the selected place again would pan back to it.
    const follow = () => {
      const place = placeInAddress();
      if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
    };
    addEventListener("popstate", follow);
    return () => removeEventListener("popstate", follow);
  }, [maplace]);
  return null;
}

/** The line under the map: a link opening on the place picked, on this map, or a prompt for one. */
function PlaceLink() {
  const maplace = useMaplace();
  const id = useSyncExternalStore(maplace.subscribe, () => maplace.getSnapshot().selectedId);
  if (id === undefined) return <p>Pick a place for a link to it.</p>;
  const address = new URL(location.href);
  address.searchParams.set(PLACE, id);
  address.hash = "link-to-place-maplibre-react-root";
  return (
    <p>
      Link to this place: <a href={address.href}>{address.search}</a>
    </p>
  );
}

function LinkToPlace() {
  return (
    <MaplaceProvider
      locations={locations}
      defaultSelectedId={placeInAddress()}
      onSelectionChange={writeAddress}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createMapLibreAdapter} className="map" />
        <LocationList fitAll fitAllLabel="View all" />
      </div>
      <PlaceLink />
      <FollowAddress />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("link-to-place-maplibre-react-root") as HTMLElement).render(
  <StrictMode>
    <LinkToPlace />
  </StrictMode>,
);
```

### React on Google

`packages/maplace/examples/link-to-place/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>
<style>
  #link-to-place-react-root .map-and-list { display: flex; height: 24rem; }
  #link-to-place-react-root .map { flex: 1 1 auto; min-width: 0; }
  #link-to-place-react-root [role="listbox"] { flex: 0 1 16rem; }
  /* On a phone the list goes under the map, as the element's does. */
  @media (width < 40rem) {
    #link-to-place-react-root .map-and-list { flex-direction: column; }
    #link-to-place-react-root [role="listbox"] { flex: none; max-height: 40%; }
  }
</style>
<div id="link-to-place-react-root"></div>
<script type="module" src="./react.tsx"></script>
```

`packages/maplace/examples/link-to-place/react.tsx`

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

const PLACE = "place-react";
const locations: Location[] = [
  { id: "rome", lat: 41.9028, lng: 12.4964, title: "Rome" },
  { id: "milan", lat: 45.4642, lng: 9.19, title: "Milan" },
  { id: "naples", lat: 40.8518, lng: 14.2681, title: "Naples" },
  { id: "turin", lat: 45.0703, lng: 7.6869, title: "Turin" },
];

/** The place the address names, if there is one: a link can name anything. */
function placeInAddress(): string | undefined {
  const id = new URLSearchParams(location.search).get(PLACE);
  return locations.find((place) => place.id === id)?.id;
}

/** A new history entry for a place picked, unless the address says so already. */
function writeAddress({ id }: { readonly id: string | undefined }): void {
  if (id === placeInAddress()) return;
  const address = new URL(location.href);
  if (id === undefined) address.searchParams.delete(PLACE);
  else address.searchParams.set(PLACE, id);
  history.pushState(null, "", address);
}

/** Back and forward select what the address names then. */
function FollowAddress() {
  const maplace = useMaplace();
  useEffect(() => {
    // Only on a change: selecting the selected place again would pan back to it.
    const follow = () => {
      const place = placeInAddress();
      if (place !== maplace.getSnapshot().selectedId) maplace.select(place);
    };
    addEventListener("popstate", follow);
    return () => removeEventListener("popstate", follow);
  }, [maplace]);
  return null;
}

/** The line under the map: a link opening on the place picked, on this map, or a prompt for one. */
function PlaceLink() {
  const maplace = useMaplace();
  const id = useSyncExternalStore(maplace.subscribe, () => maplace.getSnapshot().selectedId);
  if (id === undefined) return <p>Pick a place for a link to it.</p>;
  const address = new URL(location.href);
  address.searchParams.set(PLACE, id);
  address.hash = "link-to-place-react-root";
  return (
    <p>
      Link to this place: <a href={address.href}>{address.search}</a>
    </p>
  );
}

function LinkToPlace() {
  return (
    <MaplaceProvider
      locations={locations}
      defaultSelectedId={placeInAddress()}
      onSelectionChange={writeAddress}
    >
      <div className="map-and-list">
        <MaplaceMap createAdapter={createGoogleAdapter} className="map" />
        <LocationList fitAll fitAllLabel="View all" />
      </div>
      <PlaceLink />
      <FollowAddress />
    </MaplaceProvider>
  );
}

createRoot(document.getElementById("link-to-place-react-root") as HTMLElement).render(
  <StrictMode>
    <LinkToPlace />
  </StrictMode>,
);
```
