# Add Mountaya to your MapLibre map

> Canonical URL: https://docs.mountaya.com/en/apis/tiles/maplibre-overlays/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Give an existing MapLibre GL JS map Mountaya's base map, 3D relief and overlays with the Tile API, and let readers switch an overlay on and off.

Your app already draws a MapLibre GL JS map. In this tutorial it gets Mountaya's outdoor base map, 3D relief, and the hillshade overlay, with a button to switch it on and off.

![A MapLibre map with Mountaya's topographic base map and its layers panel](https://docs.mountaya.com/examples/tutorial-maplibre-overlays.webp)

You need a publishable key with the `tiles` scope, from **Organization → API keys** in the [Mountaya app](https://app.mountaya.com/api-keys). The Tile API comes with an agreement, which also lists the overlays your organization may draw.

No MapLibre app yet? Start one:

```bash
npx create-vite@latest my-map --template vanilla && cd my-map && npm install maplibre-gl@6.18.0
```

**1. See what your key can draw**

The layer catalog lists the base maps, the elevation source, and the overlays your organization may draw.

**cURL**

```bash
curl -s https://tiles.mountaya.com/v1/tile-layers \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  | jq '{terrains: [.data.terrains[] | {slug, style: .variants.light.style.url}], elevation: .data.elevation.url, overlays: [.data.overlays[] | .children[]?.slug]}'
```

**TypeScript**

```typescript
import { Mountaya } from "@mountaya/client";

const mountaya = new Mountaya({
  credential: { publishableKey: process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "" },
});

const { data: catalog } = await mountaya.tiles.getTileLayers();

for (const terrain of catalog.terrains) {
  console.log(terrain.slug, terrain.variants.light.style.url);
}
console.log(catalog.elevation.url);
console.log(catalog.overlays.flatMap((group) => group.children ?? []).map((overlay) => overlay.slug));
```

**Python**

```python
import os

import requests

catalog = requests.get(
    "https://tiles.mountaya.com/v1/tile-layers",
    headers={"X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
    timeout=10,
).json()["data"]

for terrain in catalog["terrains"]:
    print(terrain["slug"], terrain["variants"]["light"]["style"]["url"])
print(catalog["elevation"]["url"])
print([overlay["slug"] for group in catalog["overlays"] for overlay in group.get("children") or []])
```

**Response**

```json
{
  "terrains": [
    {
      "slug": "topo",
      "style": "https://tiles.mountaya.com/v1/terrains/topo/light/style"
    },
    {
      "slug": "winter",
      "style": "https://tiles.mountaya.com/v1/terrains/winter/light/style"
    },
    {
      "slug": "satellite",
      "style": "https://tiles.mountaya.com/v1/terrains/satellite/light/style"
    }
  ],
  "elevation": "https://tiles.mountaya.com/v1/elevation/tiles.json",
  "overlays": [
    "pois",
    "hillshade"
  ]
}
```

Overlays come in groups. Your organization's list may hold more, such as `steepness` or the weather forecasts.

- `GET https://tiles.mountaya.com/v1/tile-layers` under the `tiles` scope answers `terrains`, `elevation`, `overlays`, `itineraries` and `zones`. Under a key, `overlays` lists only what the organization's allowlist admits; an overlay outside it answers `403` on its specification and tiles. A new organization's allowlist is empty until the agreement lists slugs.
- `overlays` is a list of groups; each group's `children` are the overlays, each with `slug`, `locales` (a localized `name` per language), `capabilities` (`timestamp` for forecast overlays) and `sources`.
- Read every address from the catalog rather than writing it: a terrain's `variants.light.style.url` and `variants.dark.style.url`, and `elevation.url` (a TileJSON for a `raster-dem` source, `tile_size` 512).

**2. Switch the base map**

Point your map's `style` at a Mountaya terrain, and add your key to every request the map makes to the Tile API. The map fetches its tiles, icons and fonts on its own and cannot send headers, so the key rides in each address instead.

```js
import * as maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";

const KEY = "pk_your_publishable_key";

// Adds your key to an address on the Tile API, once, and leaves every other address alone.
const withKey = (url) =>
  url.startsWith("https://tiles.mountaya.com/") && !url.includes("publishable_key=")
    ? `${url}${url.includes("?") ? "&" : "?"}publishable_key=${KEY}`
    : url;

const map = new maplibregl.Map({
  container: "map",
  style: withKey("https://tiles.mountaya.com/v1/terrains/topo/light/style"),
  center: [6.8712, 45.9231],
  zoom: 12,
  pitch: 55,
  transformRequest: (url) => ({ url: withKey(url) }),
});
```

Keep your own options as they are: only `style` and `transformRequest` change.

- Without `transformRequest`, every tile, sprite and glyph request the style triggers answers `401`: a renderer cannot set `X-API-Key`, so the key rides the query string as `publishable_key`. Join with `&` when an address already carries a query string, add it once (the check on `publishable_key=` keeps the transform from adding it a second time), and leave other hosts untouched, so your own sources never receive the key.
- Add `session_token` beside the key where the organization requires one (the `require_session_token` rule); a token minted without `user_id` draws what the key alone does.
- The style document is a complete MapLibre style, answered unwrapped. To switch terrain or theme, call `map.setStyle()` with another address from the catalog; sources and layers you added must be added again once the new style loads.
- The same code works on Mapbox GL JS and the MapTiler SDK, which share the style API. Construct those with their own credentials; the Mountaya key authenticates Mountaya requests only.
- A publishable key ships in the page by design, and works only on the pages your allowed domains list, under **Organization → Security**. A request from any other origin answers `403`, and so does every page while the list is empty: list your site, and `localhost` with its port while you develop.

**3. Add 3D relief**

Once the style has loaded, add the elevation source from the catalog and drape the map over it.

```js
map.on("load", () => {
  map.addSource("mountaya-elevation", {
    type: "raster-dem",
    url: withKey("https://tiles.mountaya.com/v1/elevation/tiles.json"),
    tileSize: 512,
  });
  map.setTerrain({ source: "mountaya-elevation", exaggeration: 1.2 });
});
```

Leave this step out for a flat map.

- The elevation TileJSON describes a `raster-dem` source whose tiles are `/v1/elevation/{z}/{x}/{y}`; MapLibre reads `encoding` from it (default `mapbox`). `transformRequest` adds the key to the TileJSON and to every tile.
- Base-map and elevation requests are recorded under the resource type `terrain` and never counted toward the per-minute limit or the monthly allowance; a separate bound of 6,000 a minute per client IP address applies (policy `"address"`, `429` with `Retry-After`).

**4. Draw an overlay**

Each overlay has a specification: the sources and layers to add, styled already. Fetch it with your key, then add what it lists.

```js
async function addOverlay(slug) {
  const response = await fetch(`https://tiles.mountaya.com/v1/overlays/${slug}/specification`, {
    headers: { "X-API-Key": KEY },
  });
  const { data } = await response.json();
  const layerIds = [];

  for (const source of data.sources) {
    map.addSource(source.id, {
      type: source.type,
      tiles: source.tiles.map(withKey),
      minzoom: source.zoom_min,
      maxzoom: source.zoom_max,
      attribution: source.attribution,
      ...(source.size ? { tileSize: source.size } : {}),
    });

    for (const layer of source.layers) {
      map.addLayer({
        id: layer.id,
        type: layer.type,
        source: source.id,
        ...(layer.source_layer ? { "source-layer": layer.source_layer } : {}),
        ...(layer.filter ? { filter: layer.filter } : {}),
        minzoom: layer.zoom_min,
        maxzoom: layer.zoom_max,
        paint: layer.paint ?? {},
        layout: layer.layout ?? {},
      });
      layerIds.push(layer.id);
    }
  }

  return layerIds;
}
```

Call it once the style has loaded, as the next step does. Hillshade is a `raster-dem` source with one `hillshade` layer, drawn from zoom 8 up.

- The tile templates in a specification carry no credential: `withKey` adds the key to each template (and `transformRequest` would add it to any request it missed). Without a key, every overlay tile answers `401`.
- Each source has `id`, `type` (`vector`, `raster` or `raster-dem`), `tiles`, `zoom_min`, `zoom_max`, `attribution`, `layers`, and `size` (256 or 512, raster kinds only) for `tileSize`. Each layer has `id`, `type`, `source_layer` (MapLibre's `source-layer`, empty for raster layers), `zoom_min`, `zoom_max`, `paint` and `layout` (either may be null: pass `{}`), and an optional `filter`.
- A specification of an overlay outside the organization's allowlist answers `403`. A forecast overlay takes a `timestamp` (RFC 3339) on its tile URLs; replace the source's tiles when the selected time changes.
- Add overlays after the style has loaded, and again after any `setStyle()`.

**5. Let readers switch it off**

Draw the overlay once the style has loaded. Its layers are ordinary layers, so a button toggles their `visibility`.

```js
const button = document.querySelector("#hillshade-toggle");

map.on("load", async () => {
  const layerIds = await addOverlay("hillshade");
  let visible = true;

  button.addEventListener("click", () => {
    visible = !visible;
    for (const id of layerIds) {
      map.setLayoutProperty(id, "visibility", visible ? "visible" : "none");
    }
    button.textContent = visible ? "Hide hillshade" : "Show hillshade";
  });
});
```

Add `<button id="hillshade-toggle">Hide hillshade</button>` beside the map's container, as the whole page below does. Readers can then compare the map with and without relief shading.

## The whole page

Both files, as the steps build them. Start the app with `npm run dev`.

**index.html**

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Mountaya on MapLibre</title>
    <style>
      html,
      body,
      #map {
        height: 100%;
        margin: 0;
      }
      #hillshade-toggle {
        position: absolute;
        top: 12px;
        left: 12px;
        z-index: 1;
      }
    </style>
  </head>
  <body>
    <button id="hillshade-toggle" type="button">Hide hillshade</button>
    <div id="map"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
```

**src/main.js**

```js
import * as maplibregl from "maplibre-gl";
import "maplibre-gl/dist/maplibre-gl.css";

const KEY = "pk_your_publishable_key";

// Adds your key to an address on the Tile API, once, and leaves every other address alone.
const withKey = (url) =>
  url.startsWith("https://tiles.mountaya.com/") && !url.includes("publishable_key=")
    ? `${url}${url.includes("?") ? "&" : "?"}publishable_key=${KEY}`
    : url;

const map = new maplibregl.Map({
  container: "map",
  style: withKey("https://tiles.mountaya.com/v1/terrains/topo/light/style"),
  center: [6.8712, 45.9231],
  zoom: 12,
  pitch: 55,
  transformRequest: (url) => ({ url: withKey(url) }),
});
map.on("load", () => {
  map.addSource("mountaya-elevation", {
    type: "raster-dem",
    url: withKey("https://tiles.mountaya.com/v1/elevation/tiles.json"),
    tileSize: 512,
  });
  map.setTerrain({ source: "mountaya-elevation", exaggeration: 1.2 });
});
async function addOverlay(slug) {
  const response = await fetch(`https://tiles.mountaya.com/v1/overlays/${slug}/specification`, {
    headers: { "X-API-Key": KEY },
  });
  const { data } = await response.json();
  const layerIds = [];

  for (const source of data.sources) {
    map.addSource(source.id, {
      type: source.type,
      tiles: source.tiles.map(withKey),
      minzoom: source.zoom_min,
      maxzoom: source.zoom_max,
      attribution: source.attribution,
      ...(source.size ? { tileSize: source.size } : {}),
    });

    for (const layer of source.layers) {
      map.addLayer({
        id: layer.id,
        type: layer.type,
        source: source.id,
        ...(layer.source_layer ? { "source-layer": layer.source_layer } : {}),
        ...(layer.filter ? { filter: layer.filter } : {}),
        minzoom: layer.zoom_min,
        maxzoom: layer.zoom_max,
        paint: layer.paint ?? {},
        layout: layer.layout ?? {},
      });
      layerIds.push(layer.id);
    }
  }

  return layerIds;
}
const button = document.querySelector("#hillshade-toggle");

map.on("load", async () => {
  const layerIds = await addOverlay("hillshade");
  let visible = true;

  button.addEventListener("click", () => {
    visible = !visible;
    for (const id of layerIds) {
      map.setLayoutProperty(id, "visibility", visible ? "visible" : "none");
    }
    button.textContent = visible ? "Hide hillshade" : "Show hillshade";
  });
});
```

- The whole `src/main.js` is the four step blocks in order: the map, the relief's `load` handler, `addOverlay`, and the overlay's `load` handler with the toggle. Two `load` handlers are fine; adding the same overlay twice is not (`Source "…" already exists`).
- `maplibre-gl` 6 publishes named exports only: `import * as maplibregl from "maplibre-gl"` (or `import { Map } from "maplibre-gl"`); a default import fails to load.
- In a React app, the `@mountaya/elements-react` package draws the same base map, overlays and a layers panel with no style code: see [Show a map with controls](https://docs.mountaya.com/en/sdks/typescript/map.md). To keep your own MapLibre map and only authenticate it, `createTransformRequest({ publishableKey })` from `@mountaya/elements` builds the same transform, and `applySpecification(map, specification)` adds a specification's sources and layers.

## Next steps

- [Overlays](https://docs.mountaya.com/en/apis/tiles/overlays.md): The catalog, forecasts and the time parameter.
- [Integration](https://docs.mountaya.com/en/apis/tiles/integration.md): Mapbox GL JS, the MapTiler SDK and deck.gl.
