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 = L.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("https://layer.clockworkmicro.com/v1/terrainlayers", {
      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,
});
instance.setOpacity(1);
instance.addTo(map);

Learn more about our terrain tiles offerings: https://www.clockworkmicro.com/services/terrain-tiles

About

Clockwork Micro is based in Seattle and Paris.

Services

Contact

Email:

info@clockworkmicro.com
Copyright2024Clockwork Micro. All rights reserved.

Clockwork Micro