Skip to content

Draw a Car Route in Leaflet

This example calculates a car route between two points and draws it on a Leaflet map. Each turn instruction is shown as a clickable marker with a popup.

Dependencies: mapbox-polyline

let map = L.map('map').setView([47.270537, 11.413507], 14);
    L.tileLayer('https://rtc-cdn.maptoolkit.net/rtc/maptoolkit-maptoolkit.summer/{z}/{x}/{y}{ratio}.png?api_key=YOUR_API_KEY', {
      ratio: L.Browser.retina ? '@2x' : '',
      maxZoom: 18,
      attribution: '© <a href="https://www.maptoolkit.com">Maptoolkit</a> © <a href="https://www.openstreetmap.org/copyright">OSM</a>'
    }).addTo(map);

    let start = [11.393712, 47.259938];
    let end   = [11.430896, 47.28187];
    let url = new URL('https://routing.maptoolkit.net/route');
    url.searchParams.append('point', `${start[1]},${start[0]}`);
    url.searchParams.append('point', `${end[1]},${end[0]}`);
    url.searchParams.append('routeType', 'car');
    url.searchParams.append('api_key', 'YOUR_API_KEY');

    fetch(url)
      .then(r => r.json())
      .then(route => {
        let path = route.paths[0];
        let coordinates = polyline.decode(path.points);
        new L.Polyline(coordinates, { color: '#2a3561', weight: 5 }).addTo(map);
        path.instructions.forEach(instruction => {
          let marker = new L.Marker(instruction.coordinate, {
            icon: new L.Icon({ iconUrl: 'https://static.maptoolkit.net/sprites/toursprung/route-via.svg', iconSize: [12, 12], iconAnchor: [6, 6] })
          }).addTo(map);
          marker.bindPopup(L.popup().setContent(`<p>${instruction.text}</p>`));
        });
        new L.Marker(coordinates[coordinates.length - 1], {
          interactive: false,
          icon: new L.Icon({ iconUrl: 'https://static.maptoolkit.net/sprites/toursprung/marker.svg', iconSize: [30, 29], iconAnchor: [15, 29] })
        }).addTo(map);
      });
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" />
  <style>
    body { width: 100%; height: 100%; padding: 0; margin: 0; }
    #map { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <div id="map"></div>
  <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mapbox-polyline/1.1.1/polyline.min.js"></script>
  <script>
    let map = L.map('map').setView([47.270537, 11.413507], 14);
    L.tileLayer('https://rtc-cdn.maptoolkit.net/rtc/maptoolkit-maptoolkit.summer/{z}/{x}/{y}{ratio}.png?api_key=YOUR_API_KEY', {
      ratio: L.Browser.retina ? '@2x' : '',
      maxZoom: 18,
      attribution: '© <a href="https://www.maptoolkit.com">Maptoolkit</a> © <a href="https://www.openstreetmap.org/copyright">OSM</a>'
    }).addTo(map);

    let start = [11.393712, 47.259938];
    let end   = [11.430896, 47.28187];
    let url = new URL('https://routing.maptoolkit.net/route');
    url.searchParams.append('point', `${start[1]},${start[0]}`);
    url.searchParams.append('point', `${end[1]},${end[0]}`);
    url.searchParams.append('routeType', 'car');
    url.searchParams.append('api_key', 'YOUR_API_KEY');

    fetch(url)
      .then(r => r.json())
      .then(route => {
        let path = route.paths[0];
        let coordinates = polyline.decode(path.points);
        new L.Polyline(coordinates, { color: '#2a3561', weight: 5 }).addTo(map);
        path.instructions.forEach(instruction => {
          let marker = new L.Marker(instruction.coordinate, {
            icon: new L.Icon({ iconUrl: 'https://static.maptoolkit.net/sprites/toursprung/route-via.svg', iconSize: [12, 12], iconAnchor: [6, 6] })
          }).addTo(map);
          marker.bindPopup(L.popup().setContent(`<p>${instruction.text}</p>`));
        });
        new L.Marker(coordinates[coordinates.length - 1], {
          interactive: false,
          icon: new L.Icon({ iconUrl: 'https://static.maptoolkit.net/sprites/toursprung/marker.svg', iconSize: [30, 29], iconAnchor: [15, 29] })
        }).addTo(map);
      });
  </script>
</body>
</html>

Use the prompt below with any LLM to get the same result. Make sure the Maptoolkit MCP server is connected first — check out AI Integration & MCP to get started.

Use the Maptoolkit Connector. Create an interactive map with a route from [11.393712, 47.259938] to [11.430896, 47.28187] using Leaflet.

How it works

The API takes point as lat,lng. The arrays in this example are [lng, lat], which is why they are swapped when the URL is built. Leaflet also works in [lat, lng], so the decoded route needs no further reordering here, which is not true of the MapLibre version of this example.

The route geometry is an encoded polyline, not GeoJSON. path.points is a compressed string, which is why the page loads a polyline library and calls polyline.decode(). Skip that step and you are trying to draw a string.

The response carries paths as an array. paths[0] is the best route; alternatives appear behind the alternative_route parameters.

path.instructions is the turn-by-turn list. Each instruction points at an index in the decoded coordinate array, which is how a marker gets placed at the right corner.

Next steps

The route you have is the default one. The parameters in the Routing API reference are what make it yours: routeType for bike, foot, hike or transit, alternatives when you want to offer a choice, and GPX or KML output when the result has to leave the browser.

The natural companion is elevation. A cycling or hiking route without a climb profile answers half the question, and the Elevation API takes the decoded geometry directly. For “where can I get” rather than “how do I get there”, the Isochrone API answers a different question with the same key.