MapSnippets logoMapSnippets logo

Line Layers with MapLibre GL JS

MapLibre GL JS

Draw a route or path on the map using a GeoJSON LineString source and a line layer with custom paint properties.

progress_activityLoading map...
const map = new maplibregl.Map({
  container: 'map',
  style: 'https://api.maptiler.com/maps/streets-v4/style.json?key=YOUR_MAPTILER_KEY',
  center: [14.42, 50.08],
  zoom: 12
});
map.on('load', () => {
  map.addSource('route', {
    type: 'geojson',
    data: { type: 'Feature', geometry: { type: 'LineString',
      coordinates: [[14.395, 50.095], [14.410, 50.088], [14.425, 50.080], [14.445, 50.075]] } }
  });
  map.addLayer({
    id: 'route-line', type: 'line', source: 'route',
    layout: { 'line-join': 'round', 'line-cap': 'round' },
    paint: { 'line-color': '#2196F3', 'line-width': 4 }
  });
});

How it works

Add a GeoJSON source with a LineString geometry, then create a line layer to render it. The layout properties control how line segments join (line-join) and how endpoints look (line-cap). Setting both to round produces smooth, rounded lines.

The paint properties control appearance: line-color sets the stroke color and line-width the thickness in pixels. You can also use line-opacity, line-dasharray, and line-gradient for advanced styling.

All source and layer additions must happen inside map.on('load', ...) to ensure the style is ready.

Key APIs

API Description Docs
line layer type Render LineString geometries maplibre.org docs
line-dasharray Create dashed or dotted lines maplibre.org docs
line-gradient Color gradient along the line maplibre.org docs

FAQ

How do I use a dashed line?

Add 'line-dasharray': [4, 2] to the paint properties. The values define dash and gap lengths.

Can I animate a line?

Yes. Update the GeoJSON source with source.setData() on each frame, progressively adding coordinates to simulate drawing.

Common mistakes

  • Forgetting lineMetrics: true on the source when using line-gradient: gradients require line metrics
  • Using [lat, lng] order in coordinates instead of GeoJSON [lng, lat]
  • Adding the layer outside the load event: causes “Style is not done loading” errors
auto_awesome

Build maps using MapLibre GL JS with AI

Generate code like this line layers with maplibre gl js example using the MapLibre GL JS skill in your IDE.