DEV Community

Cover image for How to Create Bubble Maps in JavaScript
andreykh for AnyChart

Posted on • Updated on • Originally published at anychart.com

How to Create Bubble Maps in JavaScript

Map charts are a great way to put data in a geographical context. And they are not difficult to create! I am eager to demonstrate that by walking you through the creation of a bubble map, one of the most popular types data maps, with the help of JavaScript.

A bubble map is a combination of a bubble chart and a geographical map. It uses circles of different sizes (and sometimes colors) to indicate numeric values relating to locations or territories.

In this tutorial, I will be visualizing the data on gasoline prices across the United States. They saw record highs this summer after a surge fueled by the outbreak of the Russia–Ukraine conflict. The first, basic bubble map will display the gas prices in July by state. The final one will add the magnitude of the change since February 23, one day before Russia launched an attack on Ukraine.

Follow along and you’ll learn to build beautiful interactive maps in JS with ease and no problem!

Final JS Bubble Map Preview

Check out the final result of the JavaScript-based bubble mapping in this tutorial:

Custom bubble map built along this guide

Basic JavaScript Bubble Map in 4 Steps

Creating interactive JS bubble maps from scratch might seem daunting and tedious. But I will show you how to do it with ease and fun.

Generally speaking, there are four fundamental steps to build a basic bubble map, just like any other chart: prepare a web page, add JavaScript files, load data, and write some charting code. Let’s do that!

1. Prepare a web page

First things first. I create a blank web page. Then I add a block-level HTML element (div) as the placeholder for the bubble map; I also give it a unique id (container) and set some styling.

Here is how my HTML page looks now:

<html>
  <head>
    <title>JavaScript Bubble 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

I want the visualization to be displayed over the entire screen. So I’ve set the width and height of the placeholder div element as 100%. Feel free to change that as you see fit in your situation.

2. Add JavaScript files

Second, all the JS files that will be used to make a bubble map must be added to the web page. That is done by adding the corresponding links wrapped in the script tags to the head section.

To make it all quick and straightforward, I will use the JavaScript charting library called AnyChart, precisely the AnyMap solution. So, I include the two modules needed to build bubble maps, “core” and “geo maps”, as well as the geodata file for the United States.

Then I prepare a place for the future JS mapping code itself by adding the script tag to the body section (basically, this tag can be put anywhere across the page).

See what my HTML page looks like now:

<html>
  <head>
    <title>JavaScript Bubble Map</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-map.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/geodata/countries/united_states_of_america/united_states_of_america.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>
      // The place for the JavaScript bubble mapping code.
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

3. Load data

Third, I add my data.

There are multiple data formats that can be used. I decided to go with JSON and created a data file with the prices of regular gasoline across the U.S., by state, which you can take a look at here.

I will need two more JS files for using the data. One is the Data Adapter for loading the JSON data file itself. And the other is Proj4js for transforming the coordinates to plot bubbles over the respective geographical states. I reference them in the head section together with the other scripts.

<script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-data-adapter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.3.15/proj4.js"></script>
Enter fullscreen mode Exit fullscreen mode

Then I use the anychart.data.loadJsonFile() function to load the JSON file, within the script tag previously placed in the body section.

anychart.data.loadJsonFile( 'https://gist.githubusercontent.com/shacheeswadia/eead370d79e0f20df5148b79b6887393/raw/fba29e3dcf1806cab770e845546a136a924cf1d5/dataBubbleMap2.json', function (data) {})
Enter fullscreen mode Exit fullscreen mode

4. Write some charting code

The fourth step is for populating the script tag in the body section of the web page with the code to visualize the JS-based bubble map. Actually, just a few quick lines will be enough!

All the code is to be wrapped into the anychart.onDocumentReady() function so that the page is fully loaded before anything else is executed.

Inside it, to begin with, I load the data as shown in the 3rd step. Then I create a map chart instance using the built-in function and add the geodata for the United States.

<script>

  anychart.onDocumentReady(function() {

    // load the data
    anychart.data.loadJsonFile( 'https://gist.githubusercontent.com/shacheeswadia/eead370d79e0f20df5148b79b6887393/raw/fba29e3dcf1806cab770e845546a136a924cf1d5/dataBubbleMap2.json',
    function (data) {

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

      // add the u.s. geodata
      map.geoData("anychart.maps.united_states_of_america");

    });

  });
</script>
Enter fullscreen mode Exit fullscreen mode

Since I want to denote the gas prices with bubbles, I create a bubble series and map those values as the size of the bubbles all over the map:

let series = map.bubble(
  anychart.data.set(data).mapAs({
    size: "Petrol"
  })
);
Enter fullscreen mode Exit fullscreen mode

Captions are important for better legibility. So I enable the series labels to display the names of the states and add a title.

// enable the series labels
series
  .labels()
  .enabled(true);

// set the map's title
map.title("Gasoline Prices in the United States in July 2022");
Enter fullscreen mode Exit fullscreen mode

Finally, I reference the HTML block-level element as the container for the map and draw the resulting visualization.

// set the container id
map.container("container");

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

There you go! A lovely interactive bubble map is created using JavaScript just like that! You can clearly understand which U.S. states saw the highest gas prices in July 2022.

Basic JS bubble map

I have kept the code for this basic JS bubble map in the Playground online code editor so you can take a closer look at it, add your own data, and so on. I am also putting it here below.

But don’t leave yet and do keep reading as I have much more to show you!

<html>
  <head>
    <title>JavaScript Bubble Map</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-map.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/geodata/countries/united_states_of_america/united_states_of_america.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/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 () {
        anychart.data.loadJsonFile(
          "https://gist.githubusercontent.com/shacheeswadia/eead370d79e0f20df5148b79b6887393/raw/fba29e3dcf1806cab770e845546a136a924cf1d5/dataBubbleMap2.json",
          function (data) {

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

            // add the u.s. geodata
            map.geoData("anychart.maps.united_states_of_america");

            // create a bubble series
            let series = map.bubble(
              anychart.data.set(data).mapAs({
                size: "Petrol"
              })
            );

            // enable the series labels
            series
              .labels()
              .enabled(true);

            // set the map's title
            map.title("Gasoline Prices in the United States in July 2022");

            // set the container id
            map.container("container");

            // initiate the map drawing
            map.draw();

          }
        );
      });
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Custom JS Bubble Map

There are umpteen possibilities to customize JavaScript bubble maps. Right now, I will explain and demonstrate some of them. To start with, I will color the bubbles to reflect how greatly the gas price in each state increased between February and July 2022. Then I will enhance the label placement, tooltips, coloring in the hovered state, and map title.

  1. Use colors to display the change
  2. Improve the label placement
  3. Enhance the tooltip
  4. Change the bubble color in the hovered state
  5. Customize the title

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

Top comments (0)