Use Terrain Tiles with Leaflet

Display our customizable terrain tiles in a map using the Leaflet JavaScript library.

Terrain Tiles

Once you have obtained your access token, you may now request map tiles from our mapping microservices.

Leaflet is a popular JavaScript library used to create interactive maps for the web. Because our terrain tiles microservice requires an access token, you will need to extend Leaflet's default functionality to pass the access token with every tile request. This article will describe an example implementation that achieves this functionality.

Assuming you have an HTML div with an ID of "map", start by creating a Leaflet map instance.

// Create a map instance and set the view parameters
var map ="map").setView([51.505, -0.09], 13);

Create a custom Leaflet GridLayer that correctly requests a tile and displays it on a map grid in the form of an HTML img.

L.GridLayer.TerrainLayer = L.GridLayer.extend({
  createTile: function ({ x, y, z }) {
    const tile = document.createElement("img");
    const token = "[Access Token]";
    fetch("", {
      method: "GET",
      withCredentials: true,
      // Customize the transform type and relief
      body: `z=${z}&x=${x}&y=${y}` + `&transform_type=hillshade`,
      headers: {
        Authorization: `Bearer ${token}`,
      .then((res) => {
        // Return the response as an ArrayBuffer
        return res.arrayBuffer();
      .then((data) => {
        // Convert the binary data returned from the API to a base64-encoded string
        const tileData = btoa(
          new Uint8Array(data).reduce(
            (d, byte) => d + String.fromCharCode(byte),
        // Set the tile element's source to the base64-encoded string
        tile.src = "data:;base64," + tileData;
      .catch((err) => {
        // Log any errors
        console.log("Something went wrong! ", err);
    return tile;

Finally, wrap the custom GridLayer in a function and add an instance of this to the map.

// Create a wrapper function around the custom GridLayer
L.gridLayer.terrainLayer = function (opts) {
  return new L.GridLayer.TerrainLayer(opts);
// Create an instance of the custom GridLayer and add it to the map
const instance = L.gridLayer.terrainLayer({
  maxNativeZoom: 14,
  minZoom: 0,
  maxZoom: 20,

Learn more about our terrain tiles offerings:


Clockwork Micro is based in Seattle and Paris.



Copyright2024Clockwork Micro. All rights reserved.

Clockwork Micro