DEV Community

Cover image for How to Build a Choropleth Map in JavaScript
andreykh for AnyChart

Posted on • Updated on

How to Build a Choropleth Map in JavaScript

Are you ready to learn how to create a choropleth map with JavaScript like a boss? Maps are a powerful way to visualize data, but building one from scratch can be a daunting task. Don't worry, I'm here to help!

In this tutorial, I'll guide you through the process of building a JavaScript choropleth map step by step. And to make things more interesting, we’ll use Queen Elizabeth II's state visits as an example to showcase the power of this type of map.

Get ready to impress yourself and your audience with stunning data visualizations, and let's get started on this exciting journey together!

What Is a Choropleth Map?

A choropleth map is a type of thematic map that uses color to represent values of a specific quantity within different regions or geopolitical areas. The map is divided into areas or polygons, and the color of each area represents the value of the data being visualized. Typically, darker shades of a color indicate higher values, while lighter shades represent lower values.

So as I mentioned, in this tutorial we'll be creating a JS-based choropleth map to showcase Queen Elizabeth II's state visits around the world. By using different colors to represent the number of visits in each region, we can easily identify which areas the Queen visited the most frequently. The final interactive choropleth map will look like this: JS-based choropleth map to showcase Queen Elizabeth II's state visits around the world

How to Build a Basic Choropleth Map

Creating a choropleth map with JavaScript may seem challenging, but fear not! There are just four simple steps to follow:

  1. Set up an HTML page to display the map.
  2. Add all the necessary JavaScript files.
  3. Include the data.
  4. Write the required JavaScript code to render the map.

Once you've completed these four steps, you'll have a beautiful choropleth map that accurately represents your data. So let's dive into each step in more detail and learn how to easily create a stunning JavaScript choropleth map!

1. Set up an HTML page to display the choropleth map

To start creating the choropleth map, the first step is to set up an HTML page with a div element and give it a unique ID to reference it later. I’ll set the width and height of the div element to 100% to render the map on the whole page, but you can adjust these values to suit your needs. This div element will be the container for the chart, and the ID will be used to reference it in the JavaScript code. So, let's get started by creating the HTML page for the upcoming choropleth map!

<html>
  <head>
    <title>JavaScript Choropleth Map</title>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>
    <div id="container"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

2. Add all the necessary JavaScript files

To easily create data visualizations for the web, I use a JavaScript charting library with in-built utilities and functions. With the vast number of such JS libraries available, the process for creating charts and maps is similar in essence and logic across most of them. In this tutorial, I am using the AnyChart JS charting library as it is beginner-friendly with extensive documentation and plenty of examples to help you get started.

It is needed to link the required JS scripts in the <head> section of the HTML page. These scripts include the Core and Geo Maps modules and the file that contains geodata for the world map, all of which are available on the CDN. I'll also use two more script files to connect the data to the choropleth map. One is the Data Adapter, which will help load the data, and the other is Proj4js, a JavaScript library that will transform the coordinates from one coordinate system to another so the data can be plotted on the map accurately.

<html>
  <head>
    <title>JavaScript Choropleth Map</title>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-map.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/geodata/custom/world/world.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-data-adapter.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
    <script>
      // All the code for the JS choropleth map will come here
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Include the data

Alright, let's get the data loaded up and plotted on the JS choropleth map! First things first, I have collected the data on the state visits made by Queen Elizabeth II from Wikipedia and put it in a JSON file for easy access. You can find it here.

All the necessary files are already linked in the <head> section of the HTML page. So it’s possible to use the loadJsonFile() method inside a <script> tag in the body of the page to load the JSON file containing the Queen's state visits data.

anychart.data.loadJsonFile(<fileURL>, function (data) {});
Enter fullscreen mode Exit fullscreen mode

Great! Now that everything is set up and ready to go, it's time to move on to the main part of the journey: creating the choropleth map visualization! Let's do this!

4. Write the required JavaScript code to render the map

You can get the choropleth map rendered with just a few lines of JS code. First, make sure that all the code is inside the function anychart.onDocumentReady() so that the page is fully loaded before executing anything else. Once the data file is loaded, set the data, create the map, and set the geodata.

<script>

  anychart.onDocumentReady(function() {

    // load data from a json file
    anychart.data.loadJsonFile(
'https://gist.githubusercontent.com/shacheeswadia/8f45da54d9bf2032fee201dbfc79e0e4/raw/5d10d58f40b4a1d994cef36dbc64545ef90ead80/queenVisits.json',
      function (data) {

        // create a dataset
        let dataSet = anychart.data.set(data);

        // create a map instance
        let map = anychart.map();

        // set the geodata
        map.geoData("anychart.maps.world");

        // the rest of the JS code will be here

      });

  });

<script>
Enter fullscreen mode Exit fullscreen mode

Now, create a series with the choropleth() function and the loaded data. For the coloring, let’s set up a linear color scale with four different shades of blue based on the colors on the royal website. As per convention, the darker the shade of a country, the higher the number of visits to that region.

// create a choropleth series
let series = map.choropleth(dataSet);

// set the map colors
series
  .colorScale(
    anychart.scales.linearColor("#f2f2f2", "#42a5f5", "#1976d2", "#233580")
  );
Enter fullscreen mode Exit fullscreen mode

Finally, give a title to the map, set the container, and draw the resulting map.

// set the map title
map.title("State Visits Made by Queen Elizabeth II");

// set the container
map.container('container');

// initiate the map drawing
map.draw();
Enter fullscreen mode Exit fullscreen mode

And voila! A beautiful and functional choropleth map is ready! Check out how it looks. You can find the entire code below or view and play with it here.

Basic choropleth map

<html>
  <head>
    <title>JavaScript Choropleth Map</title>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-map.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/geodata/custom/world/world.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.1/js/anychart-data-adapter.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script>
    <style type="text/css">      
      html, body, #container { 
        width: 100%; height: 100%; margin: 0; padding: 0; 
      } 
    </style>
  </head>
  <body>  
    <div id="container"></div>
    <script>
      anychart.onDocumentReady(function () {
        // load data from a json file
        anychart.data.loadJsonFile(
"https://gist.githubusercontent.com/shacheeswadia/8f45da54d9bf2032fee201dbfc79e0e4/raw/5d10d58f40b4a1d994cef36dbc64545ef90ead80/queenVisits.json",
          function (data) {
            // create a dataset
            let dataSet = anychart.data.set(data);
            // create a map instance
            let map = anychart.map();
            // set the geodata
            map.geoData("anychart.maps.world");
            // create a choropleth series
            let series = map.choropleth(dataSet);
            // set the map colors
            series
              .colorScale(
                anychart.scales.linearColor("#f2f2f2", "#42a5f5", "#1976d2", "#233580")
              );
            // set the map title
            map.title("State Visits Made by Queen Elizabeth II");
            // set the container
            map.container("container");
            // initiate the map drawing
            map.draw();
          }
        );
      });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

How to Customize a Choropleth Map

The existing choropleth map is already impressive, but let me show you how to make it even more insightful and engaging! In the following steps, I'll demonstrate how you can customize the choropleth map to add more visual appeal and interactivity:

  1. Modify the colors on hover over map areas.
  2. Add a color legend.
  3. Improve the tooltip and the title format.
  4. Add zoom controls.

FOR A WALKTHROUGH OF THESE JS CHOROPLETH MAP CUSTOMIZATIONS, CONTINUE READING THE TUTORIAL HERE.

Top comments (1)

Collapse
 
prsaya profile image
Prasad Saya • Edited

During COVID times I had noted that choropleth maps were one of the more shown ones on the web.