Get started with mapbox-gl-legend CDN

MIT licensed

Mapbox-gl-legend is a library for rendering interactive legends in Mapbox GL JS applications.

Tags:
  • mapbox
  • mapbox-gl-js
  • legend

Stable version

Copied!

How to start using mapbox-gl-legend CDN


<!DOCTYPE html>
<html>
<head>
  <link href="https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css" rel="stylesheet">
  <script src="https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js"></script>
  <script src="https://cdn.cdnhub.io/mapbox-gl-legend/1.2.5/mapbox-gl-legend.js"></script>
  <style>
    #map {
      height: 400px;
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <script>
    mapboxgl.accessToken = 'your.mapbox.access.token';

    const map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/streets-v11',
      center: [-122.4194, 37.7749],
      zoom: 12
    });

    map.on('load', () => {
      const legend = new mapboxgl.Legend({
        container: 'legend',
        map: map
      });

      map.addControl(legend);

      map.addSource('source-id', {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              geometry: {
                type: 'Point',
                coordinates: [-122.4194, 37.7749]
              },
              properties: {
                name: 'Example Feature',
                iconImage: 'example.png',
                iconSize: [32, 32],
                iconRotate: 0,
                legendClass: 'example-legend-class'
              }
            }
          ]
        }
      });

      map.addLayer({
        id: 'example-layer',
        source: 'source-id',
        type: 'circle',
        paint: {
          'circle-radius': 5,
          'circle-color': 'red'
        }
      });

      legend.addGroup('example-legend-group', {
        title: 'Example Group',
        className: 'example-legend-group'
      });

      legend.addItem('example-legend-item', {
        name: 'Example Feature',
        type: 'circle',
        layerId: 'example-layer',
        renderer: 'circle'
      });
    });
  </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!

All versions