MapSnippets logoMapSnippets logo

Route Between Two Points with Leaflet

Leaflet

Display a driving route between two points on a Leaflet map using the OSRM routing API and L.polyline.

progress_activityLoading map...
const map = L.map('map').setView([48.86, 2.35], 12);
L.tileLayer('https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', {
  tileSize: 256,
  attribution: '&copy; <a href="https://www.maptiler.com/">MapTiler</a> &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>'
}).addTo(map);
L.marker([48.8566, 2.3522]).addTo(map).bindPopup('Start: Paris Center');
L.marker([48.8738, 2.2950]).addTo(map).bindPopup('End: Arc de Triomphe');
fetch('https://router.project-osrm.org/route/v1/driving/2.3522,48.8566;2.2950,48.8738?overview=full&geometries=geojson')
  .then(r => r.json())
  .then(data => {
    const coords = data.routes[0].geometry.coordinates.map(c => [c[1], c[0]]);
    L.polyline(coords, { color: '#2196F3', weight: 5, opacity: 0.8 }).addTo(map);
  });

How it works

The OSRM (Open Source Routing Machine) API calculates driving routes between waypoints. The URL format is router.project-osrm.org/route/v1/driving/{lng1},{lat1};{lng2},{lat2}: note that OSRM uses lng,lat order, the opposite of Leaflet’s [lat, lng].

The API returns a GeoJSON geometry with the route coordinates. Since GeoJSON uses [lng, lat] order and Leaflet expects [lat, lng], each coordinate pair is swapped with .map(c => [c[1], c[0]]) before passing to L.polyline(). The overview=full parameter ensures the complete route geometry is returned.

Key APIs

API Description Docs
OSRM Route API Calculate driving route project-osrm.org/docs
L.polyline() Draw route line leafletjs.com/reference.html#polyline

FAQ

Can I add intermediate waypoints?

Yes. Separate additional coordinates with semicolons: lng1,lat1;lng2,lat2;lng3,lat3.

Why not use MapTiler for routing?

MapTiler does not provide a routing API. OSRM is a free, open-source alternative for driving directions.

How do I show the route distance and duration?

Access data.routes[0].distance (meters) and data.routes[0].duration (seconds) from the OSRM response.

Common mistakes

  • Using lat,lng order in the OSRM URL: it requires lng,lat order
  • Forgetting to swap GeoJSON coordinates [lng, lat] to Leaflet’s [lat, lng] before drawing the polyline
  • Using overview=simplified (default): this returns a low-resolution route geometry
auto_awesome

Build maps using Leaflet with AI

Generate code like this route between two points with leaflet example using the Leaflet skill in your IDE.