Mapbox-GL plugin that automatically draws a legend from layer styles

Usage no npm install needed!

<script type="module">
  import mapboxglLegend from '';




Add a legend to a mapbox-gl map by parsing layer layout & paint expressions.


Properties currently supported:

  • fill-color
  • circle-color
  • circle-radius
  • icon-image

Expressions currently supported:

  • match
  • interpolate
  • step
  • literals

Get started

Install npm package

npm install mapboxgl-legend

Add legend control to map

import LegendControl from 'mapboxgl-legend';
import 'mapboxgl-legend/dist/index.min.css';

const legend = new LegendControl();
map.addControl(legend, 'bottom-left');

Add layers as usual, and the legend will be autogenerated

  id: 'density',
  type: 'circle',
  source: 'demographic',
  paint: {
    'circle-radius': [
      'interpolate', ['linear'],
      ['to-number', ['get', 'density']],
      100, 10,
      200, 17,
      500, 30,
      1000, 50,
      2000, 75
    'circle-color': [
      ['get', 'ethnicity'],
      'White', '#f1e8c8',
      'Black', '#443722',
      'Hispanic', '#aa9761',
      'Asian', '#e8e59d',
      /* other */ '#ccc'


A few options can be passed on legend initialization.

option type default description
collapsed Boolean false Set legend panels collapsed on load
toggler Boolean false Add button to show and hide layers
layers Array[regex] undefined List of layers to be added. If undefined all layers will be added

There are also a few options that be defined as a per-layer basis using the style metadata object.

option type description
name String Set the panel title name
unit String Add a unit to all labels
labels Object Map a value to a text that replaces it as a label
  id: 'density',
  type: 'circle',
  source: 'demographic',
  paint: { /* ... */ },
  metadata: {
    name: 'Population Density',
    unit: `k/kmĀ²`


Legend defaults to a simple design inspired by standard mapbox-gl controls, but can be tunned by changing CSS variables. Check default values in /src/_variables.scss