MapSnippets logo MapSnippets logo

Draw Polylines on a Leaflet Map

Leaflet

Connect a series of coordinates with L.polyline() on a Leaflet map and style the route or path with color, weight, and opacity options.

progress_activity Loading map...
const map = L.map('map').setView([48.86, 2.35], 13);
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);
const route = [
  [48.8584, 2.2945], [48.8606, 2.3376],
  [48.8530, 2.3499], [48.8462, 2.3464]
];
L.polyline(route, { color: '#2196F3', weight: 4, opacity: 0.8 }).addTo(map);

How to draw a polyline in Leaflet

L.polyline() draws a line through an array of [lat, lng] coordinate pairs. The second argument is a style options object where you can set color, weight (line thickness in pixels), opacity, and dashArray for dashed lines.

The polyline is added to the map like any other layer with .addTo(map). You can call .setLatLngs() to update the coordinates later, or .addLatLng() to append a new point dynamically.

Key APIs

API Description Docs
L.polyline() Draw a polyline leafletjs.com/reference.html#polyline
.setLatLngs() Update coordinates leafletjs.com/reference.html#polyline-setlatlngs

FAQ

How do I make a dashed line?

Use the dashArray option: L.polyline(coords, { dashArray: '10, 10' }). The values are dash length and gap length in pixels.

Can I fit the map to the polyline bounds?

Yes. Call map.fitBounds(polyline.getBounds()) to zoom to the extent of the line.

Common mistakes

  • Using [lng, lat] instead of [lat, lng]. Leaflet puts latitude first.
  • Setting weight: 0, which makes the line invisible even though it exists on the map
  • Forgetting that polyline coordinates must be an array of arrays, not a flat array

Build maps using Leaflet with AI

Generate code like this draw polylines on a leaflet map example using the Leaflet skill in your IDE.