Use maplibre-gl-directions plugin with Jawg Routing API

Estimated reading time: 1 minute

Use the code sample below to display a route on your map with the maplibre-gl-directions plugin.

View on GitHub

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <link href="https://unpkg.com/[email protected]/dist/maplibre-gl.css" rel="stylesheet" />
    <script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
        height: 100%;
      }
      #map {
        min-height: 500px;
        height: 100%;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script type="module">
      import MapLibreGlDirections from "https://unpkg.com/@maplibre/[email protected]/dist/maplibre-gl-directions.js";

      // Don't forget to replace <YOUR_ACCESS_TOKEN> by your own access token
      const accessToken = "<YOUR_ACCESS_TOKEN>";
      const map = new maplibregl.Map({
        container: "map",
        style: `https://api.jawg.io/styles/jawg-streets.json?access-token=${accessToken}`,
        zoom: 5,
        center: [3.47, 46.0],
        hash: true,
      }).addControl(new maplibregl.NavigationControl(), "top-right");
      // This plugin is used for right to left languages
      maplibregl.setRTLTextPlugin("https://unpkg.com/@mapbox/[email protected]/mapbox-gl-rtl-text.min.js");

      map.on("load", () => {
        const directions = new MapLibreGlDirections(map, {
          api: "https://api.jawg.io/routing/route/v1",
          profile: "car",
          requestOptions: {
            "access-token": accessToken,
            alternatives: "true",
            overview: "full",
          },
        });

        // Enable interactivity (if needed)
        directions.interactive = true;

        // Paris [lng, lat]
        const start = [2.3522, 48.8566];
        // Marseille [lng, lat]
        const end = [5.3698, 43.2965];

        // Set the waypoints programmatically
        directions.setWaypoints([start, end]);
      });
    </script>
  </body>
</html>