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
-
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 -
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 thevizData
. -
Get the population data from vizData.
-
Create the data equidistant breaks and the scale color. To do these calculations you can use any other library such as D3.js.
-
Create a function to create the choropleth map based on the breaks (limits) and color scale.
-
Create a choropleth map based on the population attribute. Change the
fill-color
property of the layer and get the color from thecreatePaintColor
function. -
Create a file called
legendControl.js
next to your.html
file. Copy the following code, paste it into thelegendControl.js
file. -
Add the mouse events listener to the map.
-
Create the legend html.
-
Create the
choroplethLegendControl
style. Add the choroplethLegendControl style to your stylesheet. -
Include the
legendControl.js
JavaScript file in the <head> of your HTML file. -
Add the
choroplethLegendControl
to the map. -
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
. -
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.
View complete source code on GitHub
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