Get started
Tutorials

Import a GPX catalog

Import a GPX catalog

A script that turns a folder of GPX files into published itineraries. Run it again after adding files, or after a crash, and it imports only what is missing.

The import script and its output

You need:

  • a publishable key with the studio-embedded scope, and your secret key, from Organization → API keys in the Mountaya app;
  • the id of a member of your organization, who the imports act as;
  • Node 22.18 or later with @mountaya/client (npm install @mountaya/client), or Python 3 with requests (pip install requests).

Map Studio comes with an agreement.

1

Put the files in a folder

The script reads every .gpx file in catalog/. To try it, save one route there:

mkdir -p catalog
cat > catalog/chamonix-argentiere.gpx <<'GPX'
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="Docs" xmlns="http://www.topografix.com/GPX/1/1">
  <trk>
    <name>Docs Chamonix to Argentière</name>
    <trkseg>
      <trkpt lat="45.9231" lon="6.8712"><ele>1037</ele></trkpt>
      <trkpt lat="45.9395" lon="6.8905"><ele>1060</ele></trkpt>
      <trkpt lat="45.9558" lon="6.9036"><ele>1110</ele></trkpt>
      <trkpt lat="45.9700" lon="6.9180"><ele>1180</ele></trkpt>
      <trkpt lat="45.9822" lon="6.9271"><ele>1252</ele></trkpt>
    </trkseg>
  </trk>
</gpx>
GPX

Each itinerary takes its name from the file's <name>, which must be unique in your organization.

2

Mint a session token for a member

Imports act as one of your members, so the script first mints a session token that names them.

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\", \"user_id\": \"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1\", \"surface\": \"studio-embedded\"}" \
  | jq -r .data.token)
Response
{
  "data": {
    "expires_at": "2026-11-09T13:56:09.864388Z",
    "token": "sess_your_session_token",
    "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1"
  }
}

3

Import each file once

For each file, the script asks for a preview, which reads the route and saves nothing. It skips a route an earlier run already imported. Otherwise it imports the route and publishes it.

import { readdir, readFile } from "node:fs/promises";

const { data: activities } = await mountaya.studio.activities.getActivities();
const hikingId =
  activities
    .flatMap((category) => category.children)
    .find((activity) => activity.slug === "hiking-and-trail")?.id ?? "";

const files = (await readdir("catalog")).filter((file) => file.endsWith(".gpx")).sort();

for (const file of files) {
  // Read the route. Nothing is saved yet.
  const form = new FormData();
  form.append("provider", "gpx");
  form.append("activity_id", hikingId);
  form.append("file", new Blob([await readFile(`catalog/${file}`)]), file);
  const { data: preview } = await mountaya.studio.itineraries.postItineraryPreview({ body: form });
  const name = preview.name.trim().slice(0, 30);

  // A route an earlier run imported keeps its name: find it rather than import it twice.
  const { data: found } = await mountaya.studio.itineraries.getItineraries({
    query: { q: name, limit: 10 },
  });
  const existing = found.find((itinerary) => itinerary.name === name);
  if (existing?.status === "published") {
    console.log(`${file}: already published as ${existing.id}`);
    continue;
  }

  let itineraryId = existing?.id;
  if (itineraryId === undefined) {
    const body = {
      name,
      activity_id: hikingId,
      is_private: false,
      segments: preview.segments.map((segment) => {
        const candidate = segment[segment.recommendation] ?? segment.linestring;
        return { mode: candidate.mode, name: segment.name, geojson: candidate.geojson };
      }),
      waypoints: preview.waypoints,
    };
    // The client sends an Idempotency-Key, and resends it if it has to retry.
    const { data: imported } = await mountaya.studio.itineraries.postItineraryImport({ body });
    itineraryId = imported.id;
  }

  await mountaya.studio.itineraries.postItineraryPublication({ itinerary_id: itineraryId });
  console.log(`${file}: published as ${itineraryId}`);
}

Save the TypeScript of steps 2 and 3 as import-catalog.ts and run node import-catalog.ts. Or save the Python as import_catalog.py and run python3 import_catalog.py. Both read MOUNTAYA_PUBLISHABLE_KEY and MOUNTAYA_SECRET_KEY from the environment.

Output
chamonix-argentiere.gpx: published as 5ee02630-e3e5-45c3-8811-e1d8933b6ead

The preview picks a mode for each stretch of the route. directions re-routes it on the trail network, and linestring keeps your points as drawn.

4

Run it again

Run the script a second time. Every route is already there, so nothing is imported twice:

Output
chamonix-argentiere.gpx: already published as 5ee02630-e3e5-45c3-8811-e1d8933b6ead

Add a file to catalog/ and run it again: only the new route is imported.

Next steps

Last updated