How to Create Bubble Maps in JavaScript
Tags: javascript, datascience, tutorial, beginners
Published: 2022-11-17 23:05:01

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](https://www.anychart.com/chartopedia/chart-type/bubble-map/), one of the most popular types [data maps](https://www.anychart.com/chartopedia/usage-type/chart-to-show-location/), with the help of JavaScript.

A bubble map is a combination of a [bubble chart](https://www.anychart.com/chartopedia/chart-type/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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdrcb1msvxf15nlstm6v.png)

## 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
<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>
```

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](https://www.anychart.com/), precisely the [AnyMap](https://www.anychart.com/products/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
<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>
```

### 3. Load data

Third, I add my data.

There are multiple [data formats](https://docs.anychart.com/Working_with_Data) that can be used. I decided to go with JSON and created a data file with the [prices](https://gasprices.aaa.com/state-gas-price-averages/) of regular gasoline across the U.S., by state, which you can take a look at [here](https://gist.githubusercontent.com/shacheeswadia/eead370d79e0f20df5148b79b6887393/raw/fba29e3dcf1806cab770e845546a136a924cf1d5/dataBubbleMap2.json).

I will need two more JS files for using the data. One is the [Data Adapter](https://docs.anychart.com/Working_with_Data/Data_Adapter) for loading the JSON data file itself. And the other is [Proj4js](https://docs.anychart.com/Maps/Map_Projections#using_proj4.js) for transforming the coordinates to plot bubbles over the respective geographical states. I reference them in the `head` section together with the other scripts.

```html
<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>
```

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

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

### 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.

```html
<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>
```

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:

```javascript
let series = map.bubble(
  anychart.data.set(data).mapAs({
    size: "Petrol"
  })
);
```

[Captions](https://www.anychart.com/blog/2017/04/05/chart-captions-title-graph-tips/) are important for better legibility. So I enable the series labels to display the names of the states and add a title.

```javascript
// enable the series labels
series
  .labels()
  .enabled(true);
      
// set the map's title
map.title("Gasoline Prices in the United States in July 2022");
```

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

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

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

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3h0wgpi010ysue1xco0z.png)

I have kept the code for this basic JS bubble map in the [Playground](https://playground.anychart.com/9266aZgG/) 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
<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>
```

## 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](https://www.anychart.com/blog/2022/11/16/bubble-maps-js/).**