Get started
Get started

Vite and React quickstart

Vite and React quickstart

A map with its controls and one of your itineraries, in one React file.

1

Create the app
npm create vite@latest my-map -- --template react-ts
cd my-map
npm install @mountaya/elements-react @mountaya/elements @mountaya/client maplibre-gl@6.16.0

2

Set your key

Create a publishable key under Organization → API keys in the Mountaya app, with the tiles and publishing scopes. A publishable key is safe in a browser bundle.

.env.local
VITE_MOUNTAYA_PUBLISHABLE_KEY=pk_your_publishable_key
VITE_MOUNTAYA_ITINERARY_ID=0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21

Use the id of one of your published itineraries.

3

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

const client = new Mountaya({
  credential: { publishableKey: import.meta.env.VITE_MOUNTAYA_PUBLISHABLE_KEY },
});

// Draws one itinerary on the map it sits in, and frames it.
const Itinerary = ({ id }: { id: string }) => {
  const map = useMountayaMap();

  useEffect(() => {
    if (map === null) return;
    const drawing = new AbortController();
    map.setItinerary(id, { fit: true, signal: drawing.signal }).catch((error: unknown) => {
      if (!drawing.signal.aborted) console.error(error);
    });
    return () => drawing.abort();
  }, [id, map]);

  return null;
};

const App = () => (
  <div style={{ height: "100dvh" }}>
    <MapView
      center={[6.8712, 45.9231]}
      client={client}
      onAccessRequired={({ status, url }) => console.warn(`${status} on ${url}`)}
      zoom={12}
    >
      <MapControls compass geolocate layers preferences zoom />
      <Itinerary id={import.meta.env.VITE_MOUNTAYA_ITINERARY_ID} />
    </MapView>
  </div>
);

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

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

4

Run it
npm run dev

Open the address Vite prints. The map opens on Chamonix, then frames your itinerary.

The controls sit inside MapView, so they find the map on their own. To read drafts or call the Data API from the page, add a session token. The examples/elements-react-map directory of the SDK repository does that.

Next steps

Last updated