How to Create a Custom Legend Map with `mapboxgl` Library in JavaScript

How can I create a map with a custom legend on it using the mapboxgl library in JavaScript?

You will need to include two new lines of code in your HTML file:

<script src="https://unpkg.com/mapbox-gl@2.9.1/dist/mapbox-gl.js"></script>
<link href="https://unpkg.com/mapbox-gl@2.9.1/dist/mapbox-gl.css" rel="stylesheet">

Create an index.html file and add the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Map with custom legend</title>
    <style>
        /* Add some basic styling to make the map and legend visible */
        #map {
            width: 600px;
            height: 400px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <!-- Create a div element for the map -->
    <div id="map"></div>

    <script src="https://unpkg.com/mapbox-gl@2.9.1/dist/mapbox-gl.js"></script>
    <link href="https://unpkg.com/mapbox-gl@2.9.1/dist/mapbox-gl.css" rel="stylesheet">

    <script>
        // Initialize the map with a custom legend
        let map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/dark-v9',
            center: [-122.084051, 37.385348],
            zoom: 12,
            zoomAnimation: true
        });

        // Add a custom legend
        let jsonLegend = {
            "fill_colour": [
                "#440154FF",
                "#3B528BFF",
                "#21908CFF",
                "#5DC963FF",
                "#FDE725FF"
            ],
            "variable": ["20.00", "23.50", "27.00", "30.50", "34.00"],
            "colour_type": "fill",
            "type": "category",
            "title": "",
            "css": []
        };

        map.addControl(new MapboxglLegend({
            jsonLegend: JSON.stringify(jsonLegend)
        }));
    </script>
</body>
</html>

This script will create a basic map with a custom legend that includes five categories based on the values in the vil_int_36 column of your dataset. The legend is displayed below the map.

Please replace the dataset and the map styles according to your requirements.

You can also use this code as a starting point to create an interactive map with multiple layers, zoom levels, and other features.

For more information on Mapboxgl and its API, please refer to the official documentation: https://docs.mapbox.com/mapbox-gl-js/api/#map


Last modified on 2023-10-16