Get started

Examples

Each recipe is self-contained. Replace the key and the ids with yours.

Switch the itinerary in React

The buttons unlock on the first mountaya:ready event, then post mountaya:setItinerary.

import { useEffect, useRef, useState } from "react";

const ORIGIN = "https://app.mountaya.com";

const ITINERARIES = [
  { id: "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21", label: "Tour du Mont-Blanc" },
  { id: "3e8a5f21-9c47-4d6b-b0e3-6a1f7d2c9b54", label: "Lac Blanc" },
];

export function ItineraryPicker() {
  const ref = useRef<HTMLIFrameElement>(null);
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const handler = (event: MessageEvent) => {
      if (event.origin !== ORIGIN || event.data?.type !== "mountaya:ready") {
        return;
      }

      setReady(true);
    };

    window.addEventListener("message", handler);

    return () => window.removeEventListener("message", handler);
  }, []);

  const select = (itineraryId: string) => {
    ref.current?.contentWindow?.postMessage(
      { type: "mountaya:setItinerary", itineraryId },
      ORIGIN,
    );
  };

  return (
    <div>
      <nav>
        {ITINERARIES.map((it) => (
          <button key={it.id} type="button" disabled={!ready} onClick={() => select(it.id)}>
            {it.label}
          </button>
        ))}
      </nav>
      <iframe
        ref={ref}
        src="https://app.mountaya.com/studio/embed?publishable_key=pk_your_publishable_key&itinerary_id=0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21"
        title="Mountaya map"
        width="100%"
        height={520}
        referrerPolicy="strict-origin-when-cross-origin"
      />
    </div>
  );
}

Switch the itinerary in plain JavaScript

The same switcher, with no framework.

<nav>
  <button type="button" data-itinerary="0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21" disabled>Tour du Mont-Blanc</button>
  <button type="button" data-itinerary="3e8a5f21-9c47-4d6b-b0e3-6a1f7d2c9b54" disabled>Lac Blanc</button>
</nav>
<iframe
  id="mountaya"
  src="https://app.mountaya.com/studio/embed?publishable_key=pk_your_publishable_key&itinerary_id=0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21"
  title="Mountaya map"
  width="100%"
  height="520"
  style="border: 0"
  referrerpolicy="strict-origin-when-cross-origin"
></iframe>
<script>
  const ORIGIN = "https://app.mountaya.com";
  const frame = document.getElementById("mountaya");
  const buttons = document.querySelectorAll("button[data-itinerary]");

  window.addEventListener("message", (event) => {
    if (event.origin !== ORIGIN || event.data?.type !== "mountaya:ready") return;
    buttons.forEach((button) => {
      button.disabled = false;
    });
  });

  buttons.forEach((button) => {
    button.addEventListener("click", () => {
      frame.contentWindow.postMessage(
        { type: "mountaya:setItinerary", itineraryId: button.dataset.itinerary },
        ORIGIN,
      );
    });
  });
</script>

Show the ready event's details

Read the content's bounds, its id and the base map from each mountaya:ready event.

import { useEffect, useState } from "react";

const ORIGIN = "https://app.mountaya.com";

interface ReadyState {
  bounds: [number, number, number, number] | null;
  itineraryId: string | null;
  terrain: string;
}

export function MapWithReadout() {
  const [state, setState] = useState<ReadyState | null>(null);
  const [failed, setFailed] = useState<string | null>(null);

  useEffect(() => {
    const handler = (event: MessageEvent) => {
      if (event.origin !== ORIGIN || event.data?.type !== "mountaya:ready") {
        return;
      }

      if (event.data.error) {
        setFailed(event.data.error);
        return;
      }

      setState({
        bounds: event.data.bounds,
        itineraryId: event.data.itineraryId,
        terrain: event.data.terrain,
      });
    };

    window.addEventListener("message", handler);

    return () => window.removeEventListener("message", handler);
  }, []);

  return (
    <div>
      <iframe
        src="https://app.mountaya.com/studio/embed?publishable_key=pk_your_publishable_key&itinerary_id=0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21"
        title="Mountaya map"
        width="100%"
        height={520}
        referrerPolicy="strict-origin-when-cross-origin"
      />
      {failed ? <p>Map failed to load: {failed}</p> : null}
      {state ? (
        <p>
          {state.terrain}, {state.itineraryId ?? "no itinerary"},{" "}
          {state.bounds ? state.bounds.join(", ") : "bounds unavailable"}
        </p>
      ) : (
        <p>Loading map…</p>
      )}
    </div>
  );
}

Renew the session token in React

A hook that answers the embed's token requests from your session endpoint, in place of the pasted script.

import { type RefObject, useEffect } from "react";

const ORIGIN = "https://app.mountaya.com";

export function useEmbedSessionToken(
  frame: RefObject<HTMLIFrameElement | null>,
  endpoint = "/api/mountaya-embed-session",
) {
  useEffect(() => {
    const handler = async (event: MessageEvent) => {
      const target = frame.current?.contentWindow;
      if (
        event.origin !== ORIGIN ||
        event.source !== target ||
        event.data?.type !== "mountaya:requestSessionToken"
      ) {
        return;
      }

      const response = await fetch(endpoint);
      if (!response.ok) {
        console.error(`The session endpoint answered ${response.status}.`);
        return;
      }

      const body = await response.json();
      const session = body.data ?? body;
      // The embed takes a token naming nobody: never hand it a member's.
      if (typeof session.token !== "string" || typeof session.user_id === "string") {
        console.error("The session endpoint answered no token, or a member's token.");
        return;
      }

      target?.postMessage(
        { type: "mountaya:setSessionToken", token: session.token, expiresAt: session.expires_at },
        ORIGIN,
      );
    };

    window.addEventListener("message", handler);

    return () => window.removeEventListener("message", handler);
  }, [frame, endpoint]);
}

Call useEmbedSessionToken(ref) in the component that renders the iframe.

Next steps

Last updated