Get started

Tutorials

Build a route planner

A planner where a hiker clicks the map to add waypoints. Each click routes the trail with the Data API, draws it, and updates the elevation profile below.

A route drawn on the map above its elevation profile

You need:

  • a publishable key with the data and tiles scopes, and your secret key, from Organization → API keys in the Mountaya app;
  • a Vite and React app. To start one:
npx create-vite@latest route-planner --template react-ts && cd route-planner && \
  npm install @mountaya/client @mountaya/client-react @mountaya/elements \
  @mountaya/elements-react @tanstack/react-query maplibre-gl@6.16.0

The Data API is self-serve. The base map comes with the Tile API, which needs an agreement.

1

Mint a session token

Every Data API request carries a session token. Your server mints it with the secret key and hands it to the page.

export MOUNTAYA_SESSION_TOKEN=$(curl -s -X POST https://api.mountaya.com/v1/sessions \
  -H "X-API-Key: $MOUNTAYA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"publishable_key\": \"$MOUNTAYA_PUBLISHABLE_KEY\"}" | jq -r .data.token)
Response
{
  "data": {
    "expires_at": "2026-11-09T13:37:04.051423Z",
    "token": "sess_your_session_token",
    "user_id": null
  }
}

Serve the session from a route such as /api/mountaya-session. Authentication has route handlers for Next.js, Express and FastAPI.

2

Route between two points

directions takes the activity and the waypoints, as [longitude, latitude], and answers the route with its figures.

curl -s https://data.mountaya.com/graphql \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "query Directions($input: DirectionsInput!) { directions(input: $input) { routes { distance duration summary elevation { ascent descent } } } }",
    "variables": {
      "input": {
        "activity": "HIKING_AND_TRAIL",
        "waypoints": [[6.8712, 45.9231], [6.9271, 45.9822]]
      }
    }
  }'
Response
{
  "data": {
    "directions": {
      "routes": [
        {
          "distance": 9005.14542243658,
          "duration": 9631.009017156648,
          "summary": "9.0 km, ~2h40m, +277m / -56m elevation, 67% path, 12% track, 8% road.",
          "elevation": {
            "ascent": 275.21426732008536,
            "descent": 53.70828803578206
          }
        }
      ]
    }
  }
}

Distances are in meters, durations in seconds and climbs in meters. The page asks for the same route, plus its geometry: a line of [longitude, latitude, elevation] positions.

3

Build the planner

Replace the src/main.tsx Vite wrote with this file.

The page builds one client over the session route, so tokens renew while the map stays mounted. Each click pins a waypoint. addDirections routes the waypoints through the same client and draws the result, and the profile draws its line.

src/main.tsx
/// <reference types="vite/client" />
import { Mountaya } from "@mountaya/client/browser";
import { useSessionToken } from "@mountaya/client-react";
import type { MountayaMap } from "@mountaya/elements";
import { MapControls, MapView, MountayaElementsProvider } from "@mountaya/elements-react";
import { ItineraryProfile } from "@mountaya/elements-react/elements";
import "@mountaya/elements-react/styles.css";
import { StrictMode, useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

// Your server route from step 1.
const mint = async () => {
  const response = await fetch("/api/mountaya-session");
  if (!response.ok) throw new Error(`The session route answered ${response.status}.`);
  return response.json();
};

type Route = Awaited<ReturnType<MountayaMap["addDirections"]>>["result"]["routes"][number];

const RoutePlanner = () => {
  const { session } = useSessionToken({ mint });
  const [client] = useState(
    () =>
      new Mountaya({
        credential: {
          publishableKey: import.meta.env.VITE_MOUNTAYA_PUBLISHABLE_KEY,
          sessionToken: session,
        },
      }),
  );
  const [map, setMap] = useState<MountayaMap | null>(null);
  const [waypoints, setWaypoints] = useState<[number, number][]>([]);
  const [route, setRoute] = useState<Route | null>(null);

  // Each click on the map adds a waypoint, up to the 45 one route takes.
  useEffect(() => {
    if (map === null) return;
    return map.on("click", ({ lngLat }) =>
      setWaypoints((current) => (current.length < 45 ? [...current, lngLat] : current)),
    );
  }, [map]);

  // Pin the waypoints, then route them and draw the route.
  useEffect(() => {
    if (map === null) return;
    map.clearMarkers();
    waypoints.forEach((lngLat, index) => {
      map.addMarker({ id: `waypoint-${index}`, label: `Waypoint ${index + 1}`, lngLat });
    });
    map.clearDirections();
    if (waypoints.length < 2) {
      setRoute(null);
      return;
    }
    map
      .addDirections({ activity: "HIKING_AND_TRAIL", waypoints })
      .then(({ result }) => setRoute(result.routes[0] ?? null))
      .catch((error: unknown) => {
        // Clearing the directions cancels a route still in flight.
        if (!(error instanceof Error && error.name === "AbortError")) console.error(error);
      });
  }, [map, waypoints]);

  return (
    <MountayaElementsProvider client={client} map={map}>
      <div style={{ height: 480 }}>
        <MapView center={[6.8712, 45.9231]} client={client} onReady={setMap} terrain="topo" zoom={12}>
          <MapControls compass layers zoom />
        </MapView>
      </div>
      <p>
        {route === null ? "Click the map to add waypoints." : route.summary}{" "}
        <button onClick={() => setWaypoints([])} type="button">
          Clear
        </button>
      </p>
      {route?.geometry ? (
        <ItineraryProfile
          axis
          segments={[{ geojson: route.geometry, id: "route", name: "Your route" }]}
          stats={["distance", "ascent", "descent"]}
          tooltip
        />
      ) : null}
    </MountayaElementsProvider>
  );
};

const root = document.getElementById("root");
if (root === null) throw new Error("index.html has no #root element.");

createRoot(root).render(
  <StrictMode>
    <RoutePlanner />
  </StrictMode>,
);

4

Run it

In development, Vite's dev server can answer /api/mountaya-session in place of your backend. This vite.config.ts does, with the secret key from its environment. Drop its resolve.conditions, which point the SDK's own example at the SDK's source.

From examples/elements-react-map/vite.config.ts
import react from "@vitejs/plugin-react";
import { defaultClientConditions, defineConfig, loadEnv, type Plugin } from "vite";

/**
 * Answers the page's `/api/mountaya-session` from the dev server, standing in for your backend.
 *
 * Minting a session token takes the secret key, and a secret key never reaches a browser: the
 * page asks a server for a token, and that server holds the key. While `vite` serves this
 * application, the dev server is that server. It reads the secret key from its own environment,
 * and Vite hands a page only the variables whose name starts with `VITE_`, so the secret key is
 * in no bundle.
 *
 * The answer is the session `POST /v1/sessions` returns, taken out of the `data` it arrives in:
 * `{ token, expires_at, user_id }`, which is what `useSessionToken`'s `mint` resolves with. The
 * session script the embed wizard copies under `require_session_token` reads this shape and the
 * API's own `{ data: { token, expires_at } }` alike, so the same endpoint answers a hosted embed's
 * page too. A built application has no dev server: its own backend serves the same address.
 *
 * The mint names no user, so the token reads what the key alone does: the published itinerary,
 * and no private or unpublished one. It still matters, since an organization that requires a
 * session token is answered nothing without one. To read a member's drafts, a backend adds
 * `user_id`, the member it signed in, read from its own session and never from the request.
 *
 * @param env The dev server's environment, as `loadEnv` reads it.
 */
const sessionEndpoint = (env: Record<string, string>): Plugin => ({
  configureServer(server) {
    server.middlewares.use("/api/mountaya-session", (_request, response) => {
      const answer = (status: number, body: unknown): void => {
        response.statusCode = status;
        response.setHeader("Content-Type", "application/json");
        response.end(JSON.stringify(body));
      };

      const publishableKey = env.VITE_MOUNTAYA_PUBLISHABLE_KEY;
      const secretKey = env.MOUNTAYA_SECRET_KEY;
      if (publishableKey === undefined || secretKey === undefined) {
        answer(500, {
          error: "Set VITE_MOUNTAYA_PUBLISHABLE_KEY (pk_…) and MOUNTAYA_SECRET_KEY (sk_…).",
        });

        return;
      }

      // Imported at the first mint and not at the top of this file, so `vite build` loads no
      // client into the process that only bundles.
      import("@mountaya/client")
        .then(({ Mountaya }) =>
          new Mountaya({ credential: { secretKey } }).admin.sessions.postSession({
            body: { publishable_key: publishableKey },
          }),
        )
        .then(({ data: session }) => answer(200, session))
        .catch((error: unknown) => answer(502, { error: String(error) }));
    });
  },
  name: "mountaya-session",
});

/**
 * The example builds against the packages' SOURCE, not their `dist`.
 *
 * `@mountaya/source` is the condition every package in this family publishes its own TypeScript
 * under, and naming it here is what makes this example a gate: a change to `MapView` or to the
 * client's credential is compiled by the next build of this application, with no build of the
 * packages in between. An application pointed at `dist` goes on succeeding against whatever was
 * built last.
 *
 * It is the one thing in this file a consumer does not copy. Their bundler resolves the published
 * `dist` under the default conditions, which is what `scripts/packaging.test.mjs` holds every
 * package to.
 */
export default defineConfig(({ mode }) => ({
  // Every variable, the unprefixed ones included: the endpoint above runs in the dev server
  // and reads the secret key there.
  plugins: [react(), sessionEndpoint(loadEnv(mode, ".", ""))],
  resolve: {
    // Vite replaces its default conditions with a list a config names, so they follow the
    // condition: without them a dependency loses `module`, `browser` and `development|production`.
    conditions: ["@mountaya/source", ...defaultClientConditions],
  },
}));

Start it with your keys, then click two points along a valley. The trail appears, with its distance, its climb and its profile.

Terminal
VITE_MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key MOUNTAYA_SECRET_KEY=sk_your_secret_key npm run dev

Next steps

Last updated