Skip to content

Add a Map Legend to MapLibre GL JS

On this page

License Version Downloads

A MapLibre GL JS control that shows a legend for the current map view: one row for each kind of feature on screen, drawn the way the map draws it. Named places, peaks and waters appear by name, in the map’s own font.

With the Maptoolkit styles the legend needs no configuration. Its rows, their labels and their order come from metadata inside the style, and that is also where you change them.

Install

npm install @maptoolkit/maplibre-legend-control maplibre-gl

Usage

import * as maplibregl from "maplibre-gl";
import { LegendControl } from "@maptoolkit/maplibre-legend-control";
import "@maptoolkit/maplibre-legend-control/style.css";

const map = new maplibregl.Map({
  container: "map",
  style: "https://styles.maptoolkit.net/maptoolkit/maptoolkit.summer.json?api_key=YOUR_API_KEY",
  center: [11.39, 47.27],
  zoom: 13,
});
map.addControl(new LegendControl());
  • The control adds a button in the bottom-left corner. Add it after the Logo Control and it sits above the Maptoolkit logo. To move it, pass a position: map.addControl(new LegendControl(), "top-left").
  • The panel opens above the button in the bottom corners and below it in the top corners. The ✕ or Escape closes it.
  • The legend updates whenever the map comes to rest. It lists only what is in view.

The control needs MapLibre GL JS 6 or later. MapLibre 6 is an ES module without a default export, so use the namespace import shown above.

Where the button goes

The button option decides where the legend opens:

buttonWhere the legend opens
"icon-text"Default. A button with an icon and the word “Legend” in a map corner.
"icon"The same button with the icon only.
"style-control"A “Legend” row at the end of the Style Control panel. The legend opens where the styles were.
"attribution"The word “Legend” in bold at the start of the attribution line, while the attribution is expanded.

For "style-control", add the style control first and pass it to the legend:

import { StyleControl } from "@maptoolkit/maplibre-style-control";

const styleControl = new StyleControl({ styles, active: "Summer" });
map.addControl(styleControl);
map.addControl(new LegendControl({ button: "style-control", styleControl }));

If the style control or the attribution control is missing, the legend logs a warning and shows its "icon-text" button instead.

Without a bundler

The package is an ES module only. To load it from a CDN, map maplibre-gl in an import map:

<link href="https://unpkg.com/maplibre-gl@^6.0.0/dist/maplibre-gl.css" rel="stylesheet" />
<link href="https://unpkg.com/@maptoolkit/maplibre-legend-control@^1.0.0/dist/maplibre-legend-control.css" rel="stylesheet" />

<script type="importmap">
  {
    "imports": {
      "maplibre-gl": "https://unpkg.com/maplibre-gl@^6.0.0/dist/maplibre-gl.mjs"
    }
  }
</script>
<script type="module">
  import * as maplibregl from "maplibre-gl";
  import { LegendControl } from "https://unpkg.com/@maptoolkit/maplibre-legend-control@^1.0.0/dist/maplibre-legend-control.js";

  const map = new maplibregl.Map({ container: "map", style, center, zoom });
  map.addControl(new LegendControl());
</script>

What the legend shows

  • Lines and areas. One row per kind of feature, for example motorway, forest or country border. The swatch uses the map’s own colors, widths, dash patterns and textures at the current zoom, together with casings and outlines.
  • Names and symbols. Places, waters and points of interest show one example per type: the most prominent one in view, in the map’s font, size and color. Road shields, route names and one-way arrows sit on their line, as on the map.
  • Links. A row can end in a small ⓘ that opens an explanation, for example of the SAC hiking scale.

A row appears only while one of its features is in view. Rows that are nearly invisible at the current zoom, such as an area that is still fading in, are left out.

Configure the rows

The legend reads two pieces of metadata, both under the key maptoolkit:legend:

  • a tag on each layer that says which row the layer belongs to, and
  • a manifest at the root of the style with the labels, the order, links and hidden rows.

The Maptoolkit styles carry both. To rename, hide or reorder rows, edit the manifest in the Expert Mode of MapMaker. Fields you do not set keep the style’s defaults:

"metadata": {
  "maptoolkit:legend": {
    "entries": {
      "road:major_dark": { "label": { "en": "Motorway" } },
      "road:minor_track": { "hidden": true }
    }
  }
}

The control works with any MapLibre style. Layers without a tag are not listed, so to put a layer of your own into the legend, give it a tag. The Legend Control page on docs.maptoolkit.org describes all fields of tags and manifest, with examples.

Options

OptionTypeDefaultDescription
buttonstring"icon-text"Where the legend opens, see Where the button goes.
styleControlStyleControl–The style control that hosts the legend with button: "style-control".
togglebooleantrueShow the button. Set false if your page has its own trigger and calls open() and close().
collapsedbooleantrueStart with the panel closed. false by default when toggle is false.
languagestringpage languageLanguage of the labels, for example "de". Falls back to English.
groupsstring[]allShow only these groups: road, water, nature, border, building, relief, place, poi.
edgeBuffernumber0.05List only names that lie fully inside the map minus this share at each edge. 0 lists all.
minOpacitynumber0.1Leave out rows whose layers are all fainter than this. 0 shows every row.
maxHeightRationumber0.6Maximum panel height as a share of the map height. The list scrolls beyond it.
maxNameWidthobject or false{ fraction: 0.5, px: 260 }How wide a name may grow before it is cut. false removes the limit.
backgroundstring"auto"Panel background: the style’s background color at the current zoom, or a CSS color.
fontsstring or falsefrom the styleURL of the stylesheet with the map’s web fonts. false if your page loads them itself.
updateDelaynumber100Delay in milliseconds between the map coming to rest and the update.

Methods

const control = new LegendControl();
map.addControl(control);

control.open(); // show the panel
control.close(); // hide it
control.toggle();
control.update(); // read the view again now
control.getModel(); // the rows as data: { groups: [{ id, label, entries: [...] }] }

To draw a legend of your own, the package also exports buildLegendModel(), parseFontStack() and fontStackToCss().

Languages

The control comes with the languages of MapMaker: English, German, Spanish, Italian, French, Hungarian, Czech, Polish, Chinese, Japanese, Korean, Hindi and Arabic. language sets the language of the row labels and of the control’s own texts.

The texts sit in the map’s locale table, like those of MapLibre’s built-in controls. A text you set there wins:

const map = new maplibregl.Map({
  container: "map",
  style,
  locale: { "LegendControl.Label": "Zeichenerklärung" },
});
KeyUsed forEnglish
LegendControl.LabelText of the buttonLegend
LegendControl.TitleAccessible name of the panelLegend
LegendControl.ToggleTooltip of the buttonShow or hide the legend
LegendControl.EmptyShown when nothing in view has a rowNothing to show in this view
LegendControl.InfoTooltip of a row’s ⓘMore about this
LegendControl.CloseTooltip of the panel’s ✕Close the legend

Styling

The panel takes the style’s background color at the current zoom, so names and swatches sit on the same ground as on the map. On a dark background the text turns light. The button has the same look as the Style Control button.

To theme the control, override its CSS custom properties:

.maplibre-legend-control {
  --legend-control-radius: 4px;
  --legend-control-color-primary: #0074d9;
}
PropertyWhat it sets
--legend-control-bg-colorPanel background (set by background)
--legend-control-radiusCorner radius of button and panel
--legend-control-color-primaryAccent color
--legend-control-toggle-sizeHeight of the button (29px, like MapLibre’s buttons)
--legend-control-toggle-bg, --legend-control-toggle-colorButton colors
--legend-control-label-font-sizeSize of the row labels
--legend-control-label-max-widthWidth at which a label wraps
--legend-control-durationSpeed of the open and close animation

The full list is in the package’s style.css.

Names are set in the map’s fonts. A Maptoolkit style names the stylesheet that serves them, and the control loads it once. Until a font arrives, the text shows in a similar generic family.

License

The Legend Control is open source under the BSD 3-Clause License.