# 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.

## How it works

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.

- **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.

## Code

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