How to display an interactive choropleth map legend control

This tutorial shows how to display an interactive choropleth map legend control.

Move the mouse over the colored boxes of the legend to filter the elements of the map. Move the mouse over a country to see the population

  1. Copy the following code, paste it into your favorite text editor, and save it as a .html file. This code is the result of doing steps 1 to 12 of the tutorial How to create a countries map with your own data

  2. Include the chroma-js JavaScript file in the <head> of your HTML file. To create the legend we will use the chroma-js library. We are going to use the library to create the color scale and create the class breaks based on the vizData.

  3. Get the population data from vizData.

  4. Create the data equidistant breaks and the scale color. To do these calculations you can use any other library such as D3.js.

  5. Create a function to create the choropleth map based on the breaks (limits) and color scale.

  6. Create a choropleth map based on the population attribute. Change the fill-color property of the layer and get the color from the createPaintColor function.

  7. Create a file called legendControl.js next to your .html file. Copy the following code, paste it into the legendControl.js file.

  8. Add the mouse events listener to the map.

  9. Create the legend html.

  10. Create the choroplethLegendControl style. Add the choroplethLegendControl style to your stylesheet.

  11. Include the legendControl.js JavaScript file in the <head> of your HTML file.

  12. Add the choroplethLegendControl to the map.

  13. We already have the legend on our map. Now we’re going to add some functionality to the legend to make it interactive and allow you to filter items on the map. Back to the legendControl.js.

  14. Finally add the functionality to show the information of the selected element on the map in the legend. Hovering over a country with data will display the population in the corresponding category in the legend.

Learn more

Check out the How to use and filter data for MapTiler Countries tutorial.

Visit the MapTiler Countries schema to know how it is organized into different thematic layers and which attribute and values each layer contains.

Consult the JavaScript Maps API reference to learn about Ramps, scales, curves.

Read the following How-tos related to choropleth maps:

How to style a choropleth map in Edit Tool

Prepare GeoJSON with attributes for choropleth map and upload GeoJSON to MapTiler Cloud

An extension of MapLibre GL JS