Draw Polylines on a Leaflet Map
LeafletDraw a styled L.polyline connecting multiple coordinates on a Leaflet map to visualize routes or paths.
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: '© <a href="https://www.maptiler.com/">MapTiler</a> © <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 it works
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 coordinate order is latitude first - Setting
weight: 0: the line will be 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.
Related Examples
- Draw Polygons on a Leaflet Map
- Route Between Two Points with Leaflet
- See how to do this in MapLibre GL JS, MapTiler SDK or OpenLayers