---
title: "How to create a choropleth Map from GeoJSON using OpenLayers | Openlayers"
description: "Create a choropleth map from GeoJSON using OpenLayers."
---

> For AI agents: a documentation index is available at [/llms.txt](https://docs.maptiler.com/llms.txt). Markdown versions of all pages are available by appending .md to any URL.

# How to create a choropleth Map from GeoJSON using OpenLayers

This tutorial will walk you through the process of adding a styled GeoJSON overlay to your map, displaying a popup on click, and creating a map legend. To demonstrate, we will be using GeoJSON formatted data from EUROSTAT that includes countries with attributes. Download the [sample data for average age at first marriage](https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson).

1.  Copy the following code, paste it into your favorite text editor, and save it as a `.html` file.
    
    ```html
    <!DOCTYPE html>
     <html>
       <head>
         <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
         <title>Display a choropleth Map from GeoJSON</title>
         <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v10.1.0/ol.css">
         <script src="https://cdn.jsdelivr.net/npm/ol@v10.1.0/dist/ol.js"></script>
         <style>
           #map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
         </style>
       </head>
       <body>
         <div id="map">
           <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
         </div>
         <script>
           const key = 'YOUR_MAPTILER_API_KEY_HERE';
    
           const attribution = new ol.control.Attribution({
             collapsible: false,
           });
    
           const source = new ol.source.TileJSON({
             url: `https://api.maptiler.com/maps/streets-v4/tiles.json?key=${key}`, // source URL
             tileSize: 512,
             crossOrigin: 'anonymous'
           });
    
           const map = new ol.Map({
             layers: [
               new ol.layer.Tile({
                 source: source
               })
             ],
             controls: ol.control.defaults.defaults({attribution: false}).extend([attribution]),
             target: 'map',
             view: new ol.View({
               constrainResolution: true,
               center: ol.proj.fromLonLat([13.39, 52.51]), // starting position [lng, lat]
               zoom: 3 // starting zoom
             })
           });
         </script>
       </body>
     </html>
    ```
    

Check out the step-by-step tutorial [How to use OpenLayers](https://docs.maptiler.com/openlayers/examples/how-to-use-openlayers/)

1.  Install the npm package.
    
    ```bash
    npm install --save ol
    ```
    
2.  Include the CSS file.
    
    If you have a bundler that can handle CSS, you can [`import`](#) the CSS or include it with a [`<link>`](#) in the head of the document via the CDN
    
    ```js
    import "ol/ol.css";
    ```
    
    ```html
    <link href='https://cdn.jsdelivr.net/npm/ol@v10.1.0/dist/ol.js' rel='stylesheet' />
    ```
    
3.  Include the following code in your JavaScript file (Example: main.js).
    
    ```js
    import Map from 'ol/Map.js';
    import View from 'ol/View.js';
    import TileLayer from 'ol/layer/Tile.js';
    import TileJSON from 'ol/source/TileJSON.js';
    import Attribution from 'ol/control/Attribution.js';
    import { defaults as defaultControls } from 'ol/control/defaults.js';
    import { fromLonLat } from 'ol/proj.js';
        
    const key = 'YOUR_MAPTILER_API_KEY_HERE';
        
    const attribution = new Attribution({
      collapsible: false,
    });
        
    const source = new TileJSON({
      url: `https://api.maptiler.com/maps/streets-v4/tiles.json?key=${key}`, // source URL
      tileSize: 512,
      crossOrigin: 'anonymous'
    });
        
    const map = new Map({
      layers: [
        new TileLayer({
          source: source
        })
      ],
      controls: defaultControls({attribution: false}).extend([attribution]),
      target: 'map',
      view: new View({
        constrainResolution: true,
        center: fromLonLat([13.39, 52.51]), // starting position [lng, lat]
        zoom: 3 // starting zoom
      })
    });
    ```
    

1.  Replace `YOUR_MAPTILER_API_KEY_HERE` with [your own API key](https://cloud.maptiler.com/account/keys/). Make sure to [secure the key](https://docs.maptiler.com/guides/credentials/api-key/#secure-key) before you publish it.
    
2.  The next is up to you. You can center your map wherever you desire (modifying the `starting position`) and set an appropriate zoom level (modifying the `starting zoom`) to match your users’ needs. Additionally, you can change the map’s look (by updating the `source URL`); choose from a range of visually appealing map styles from our extensive [MapTiler standard maps](https://cloud.maptiler.com/maps/), or create your own to truly differentiate your application.
    

1.  Add the GeoJSON layer. The following snippet creates GeoJSON layer hosted on MapTiler (check out the [How to Upload GeoJSON to MapTiler](https://docs.maptiler.com/guides/maps-apis/maps-platform/prepare-geojson-with-attributes-for-choropleth-map-and-upload-geojson-to-maptiler-cloud#PrepareGeoJSONwithattributesforchoroplethmapanduploadGeoJSONtoMapTilerCloud-UploadGeoJSONtoMapTilerCloud) tutorial). The GeoJSON used in the example contains Marriage indicators data from EUROSTAT. The dataset was filtered to just countries with some value of mean age of women at first marriage in 2019. Download the [sample data for average age at first marriage](https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson)
    
    ```js
    zoom: 3 // starting zoom
       })
     });
     const geojson = new ol.layer.Vector({
       source: new ol.source.Vector({
         format: new ol.format.GeoJSON(),
         url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
       }),
     });
     map.addLayer(geojson);
    ```
    
2.  Create the functions to get the style based on the age attribute.
    
    ```js
    zoom: 3 // starting zoom
       })
     });
     const styles = function(feature,resolution) {
       if (feature.get('age') >= 30) {color = '#8c2d04' ;}
       else if (feature.get('age') >= 29 ){color ='#d94801';}
       else if (feature.get('age') >= 28 ){color ='#f16913';}
       else if (feature.get('age') >= 27 ){color ='#fd8d3c';}
       else if (feature.get('age') >= 26 ){color ='#fdae6b';}
       else if (feature.get('age') >= 25 ){color ='#fdd0a2';}
       else if (feature.get('age') >= 24 ){color ='#fee6ce';}
       else {color = '#fff5eb';}
    
         return  [
         new ol.style.Style({
           stroke: new ol.style.Stroke({
             color: 'black',
             width: 0.7,
           }),
           fill: new ol.style.Fill({
             color: color,
           }),
         }),
       ]
     };
     const geojson = new ol.layer.Vector({
    ```
    
3.  Create a choropleth map based on the age attribute. Change the `style` property of the layer.
    
    ```js
    const geojson = new ol.layer.Vector({
       source: new ol.source.Vector({
         format: new ol.format.GeoJSON(),
         url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
       }),
       style: styles
     });
    ```
    
4.  Create the popup `html` element.
    
    ```html
    <div id="map">
         <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
         <div id="popup" class="ol-popup">
           <a href="#" id="popup-closer" class="ol-popup-closer"></a>
           <div id="popup-content"></div>
         </div>
       </div>
    ```
    
5.  Create the style for the popup
    
    ```html
    <style>
        #map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
        .ol-popup {
          position: absolute;
          background-color: white;
          box-shadow: 0 1px 4px rgba(0,0,0,0.2);
          padding: 15px;
          border-radius: 10px;
          border: 1px solid #cccccc;
          bottom: 12px;
          left: -50px;
          min-width: 280px;
        }
        .ol-popup:after, .ol-popup:before {
          top: 100%;
          border: solid transparent;
          content: " ";
          height: 0;
          width: 0;
          position: absolute;
          pointer-events: none;
        }
        .ol-popup:after {
          border-top-color: white;
          border-width: 10px;
          left: 48px;
          margin-left: -10px;
        }
        .ol-popup:before {
          border-top-color: #cccccc;
          border-width: 11px;
          left: 48px;
          margin-left: -11px;
        }
        .ol-popup-closer {
          text-decoration: none;
          position: absolute;
          top: 2px;
          right: 8px;
        }
        .ol-popup-closer:after {
          content: "✖";
        }
      </style>
    ```
    
6.  Create the overlay to anchor the popup
    
    ```js
    const key = 'YOUR_MAPTILER_API_KEY_HERE';
    
     const container = document.getElementById('popup');
     const content = document.getElementById('popup-content');
     const closer = document.getElementById('popup-closer');
     const overlay = new ol.Overlay({
       element: container,
       autoPan: {
         animation: {
           duration: 250,
         },
       },
     });
     closer.onclick = function () {
       overlay.setPosition(undefined);
       closer.blur();
       return false;
     };
    
     const source = new ol.source.TileJSON({
    ```
    
7.  Add the overlay to the map
    
    ```js
    const map = new ol.Map({
       layers: [
         new ol.layer.Tile({
           source: source
         })
       ],
       overlays: [overlay],
       controls: ol.control.defaults.defaults({attribution: false}).extend([attribution]),
       target: 'map',
       view: new ol.View({
         constrainResolution: true,
         center: ol.proj.fromLonLat([13.39, 52.51]), // starting position [lng, lat]
         zoom: 3 // starting zoom
       })
     });
    ```
    
8.  Create a function to display a popup when clicking on the geojson layer and show the information of the age attribute
    
    ```js
    map.addLayer(geojson);
     map.on('click', function (evt) {
       const features = map.getFeaturesAtPixel(evt.pixel);
       const feature = features.length ? features[0] : undefined;
       if (feature.get('age')) {
         const coordinate = evt.coordinate;
         content.innerHTML = `<h3>Average age of </br> women at first marriage</h3><p>${feature.get('age')}</p>`;
         overlay.setPosition(coordinate);
       } else {
         overlay.setPosition(undefined);
       }
     });
    ```
    
9.  Create a map legend.
    
    ```html
    <div id="map">
       <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
       <div id="popup" class="ol-popup">
         <a href="#" id="popup-closer" class="ol-popup-closer"></a>
         <div id="popup-content"></div>
       </div>
     </div>
     <div id="state-legend" class="legend">
       <h4>Mean age of </br> women at first marriage </h4>
         <div><span style="background-color: #fff5eb"></span>23</div>
         <div><span style="background-color: #fee6ce"></span>24</div>
         <div><span style="background-color: #fdd0a2"></span>25</div>
         <div><span style="background-color: #fdae6b"></span>26</div>
         <div><span style="background-color: #fd8d3c"></span>27</div>
         <div><span style="background-color: #f16913"></span>28</div>
         <div><span style="background-color: #d94801"></span>29</div>
         <div><span style="background-color: #8c2d04"></span>30</div>
     </div>
     <script>
    ```
    
10.  Create the style for the map legend.
     
     ```css
     .ol-popup-closer:after {
        content: "✖";
      }
      .legend {
        background-color: #000;
        border-radius: 3px;
        bottom: 30px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        color: #fff ;
        font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
        padding: 10px;
        position: absolute;
        right: 10px;
        z-index: 1;
      }
     
      .legend h4 {
        margin: 0 0 10px;
      }
     
      .legend div span {
        border-radius: 50%;
        display: inline-block;
        height: 10px;
        margin-right: 5px;
        width: 10px;
      }
     ```
     

### Complete source code

```html
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Display a map</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v10.1.0/ol.css">
  <script src="https://cdn.jsdelivr.net/npm/ol@v10.1.0/dist/ol.js"></script>
  <style>
    body {
      margin: 0;
      padding: 0;
    }

    #map {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
    }

    .ol-popup {
      position: absolute;
      background-color: white;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
      padding: 15px;
      border-radius: 10px;
      border: 1px solid #cccccc;
      bottom: 12px;
      left: -50px;
      min-width: 280px;
    }

    .ol-popup:after,
    .ol-popup:before {
      top: 100%;
      border: solid transparent;
      content: " ";
      height: 0;
      width: 0;
      position: absolute;
      pointer-events: none;
    }

    .ol-popup:after {
      border-top-color: white;
      border-width: 10px;
      left: 48px;
      margin-left: -10px;
    }

    .ol-popup:before {
      border-top-color: #cccccc;
      border-width: 11px;
      left: 48px;
      margin-left: -11px;
    }

    .ol-popup-closer {
      text-decoration: none;
      position: absolute;
      top: 2px;
      right: 8px;
    }

    .ol-popup-closer:after {
      content: "✖";
    }

    .legend {
      background-color: #000;
      border-radius: 3px;
      bottom: 30px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      color: #fff;
      font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
      padding: 10px;
      position: absolute;
      right: 10px;
      z-index: 1;
    }

    .legend h4 {
      margin: 0 0 10px;
    }

    .legend div span {
      border-radius: 50%;
      display: inline-block;
      height: 10px;
      margin-right: 5px;
      width: 10px;
    }
  </style>
</head>

<body>
  <div id="map">
    <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img
        src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
  <div id="state-legend" class="legend">
    <h4>Mean age of </br> women at first marriage </h4>
    <div><span style="background-color: #fff5eb"></span>23</div>
    <div><span style="background-color: #fee6ce"></span>24</div>
    <div><span style="background-color: #fdd0a2"></span>25</div>
    <div><span style="background-color: #fdae6b"></span>26</div>
    <div><span style="background-color: #fd8d3c"></span>27</div>
    <div><span style="background-color: #f16913"></span>28</div>
    <div><span style="background-color: #d94801"></span>29</div>
    <div><span style="background-color: #8c2d04"></span>30</div>
  </div>
  <script>
    const key = 'YOUR_MAPTILER_API_KEY_HERE';

    const attribution = new ol.control.Attribution({
      collapsible: false,
    });

    const container = document.getElementById('popup');
    const content = document.getElementById('popup-content');
    const closer = document.getElementById('popup-closer');
    const overlay = new ol.Overlay({
      element: container,
      autoPan: {
        animation: {
          duration: 250,
        },
      },
    });
    closer.onclick = function () {
      overlay.setPosition(undefined);
      closer.blur();
      return false;
    };

    const source = new ol.source.TileJSON({
      url: `https://api.maptiler.com/maps/dataviz-v4-dark/tiles.json?key=${key}`,
      tileSize: 512,
      crossOrigin: 'anonymous'
    });

    const map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: source
        })
      ],
      overlays: [overlay],
      controls: ol.control.defaults.defaults({ attribution: false }).extend([attribution]),
      target: 'map',
      view: new ol.View({
        constrainResolution: true,
        center: ol.proj.fromLonLat([13.39, 52.51]), // starting position [lng, lat]
        zoom: 3 // starting zoom
      })
    });

    const styles = function (feature, resolution) {
      if (feature.get('age') >= 30) { color = '#8c2d04'; }
      else if (feature.get('age') >= 29) { color = '#d94801'; }
      else if (feature.get('age') >= 28) { color = '#f16913'; }
      else if (feature.get('age') >= 27) { color = '#fd8d3c'; }
      else if (feature.get('age') >= 26) { color = '#fdae6b'; }
      else if (feature.get('age') >= 25) { color = '#fdd0a2'; }
      else if (feature.get('age') >= 24) { color = '#fee6ce'; }
      else { color = '#fff5eb'; }

      return [
        new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'black',
            width: 0.7,
          }),
          fill: new ol.style.Fill({
            color: color,
          }),
        }),
      ]
    };

    const geojson = new ol.layer.Vector({
      source: new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
      }),
      style: styles
    });
    map.addLayer(geojson);

    map.on('click', function (evt) {
      const features = map.getFeaturesAtPixel(evt.pixel);
      const feature = features.length ? features[0] : undefined;
      if (feature && feature.get('age')) {
        const coordinate = evt.coordinate;
        content.innerHTML = `<h3>Average age of </br> women at first marriage</h3><p>${feature.get('age')}</p>`;
        overlay.setPosition(coordinate);
      } else {
        overlay.setPosition(undefined);
      }
    });
  </script>
</body>

</html>
```

1.  Import the new modules needed to add the new functionality.
    
    ```js
    import Map from 'ol/Map.js';
     import View from 'ol/View.js';
     import TileLayer from 'ol/layer/Tile.js';
     import VectorLayer from 'ol/layer/Vector.js';
     import VectorSource from 'ol/source/Vector.js';
     import TileJSON from 'ol/source/TileJSON.js';
     import Style from 'ol/style/Style.js';
     import Fill from 'ol/style/Fill.js';
     import Stroke from 'ol/style/Stroke.js';
     import Attribution from 'ol/control/Attribution.js';
     import GeoJSON from 'ol/format/GeoJSON.js';
     import Overlay from 'ol/Overlay.js';
     import { defaults as defaultControls } from 'ol/control/defaults.js';
     import { fromLonLat } from 'ol/proj.js';
    ```
    
2.  Add the GeoJSON layer. The following snippet creates GeoJSON layer hosted on MapTiler (check out the [How to Upload GeoJSON to MapTiler](https://docs.maptiler.com/guides/maps-apis/maps-platform/prepare-geojson-with-attributes-for-choropleth-map-and-upload-geojson-to-maptiler-cloud#PrepareGeoJSONwithattributesforchoroplethmapanduploadGeoJSONtoMapTilerCloud-UploadGeoJSONtoMapTilerCloud) tutorial). The GeoJSON used in the example contains Marriage indicators data from EUROSTAT. The dataset was filtered to just countries with some value of mean age of women at first marriage in 2019. Download the [sample data for average age at first marriage](https://docs.maptiler.com/sdk-js/assets/Mean_age_of_women_at_first_marriage_in_2019.geojson)
    
    ```js
    const geojson = new VectorLayer({
       source: new VectorSource({
         format: new GeoJSON(),
         url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
       }),
     });
     map.addLayer(geojson);
    ```
    
3.  Create the functions to get the style based on the age attribute.
    
    ```js
    const styles = function(feature,resolution) {
       if (feature.get('age') >= 30) {color = '#8c2d04' ;}
       else if (feature.get('age') >= 29 ){color ='#d94801';}
       else if (feature.get('age') >= 28 ){color ='#f16913';}
       else if (feature.get('age') >= 27 ){color ='#fd8d3c';}
       else if (feature.get('age') >= 26 ){color ='#fdae6b';}
       else if (feature.get('age') >= 25 ){color ='#fdd0a2';}
       else if (feature.get('age') >= 24 ){color ='#fee6ce';}
       else {color = '#fff5eb';}
    
         return  [
         new ol.style.Style({
           stroke: new ol.style.Stroke({
             color: 'black',
             width: 0.7,
           }),
           fill: new ol.style.Fill({
             color: color,
           }),
         }),
       ]
     };
    ```
    
4.  Create a choropleth map based on the age attribute. Change the `style` property of the layer.
    
    ```js
    const geojson = new VectorLayer({
       source: new VectorSource({
         format: new GeoJSON(),
         url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
       }),
       style: styles
     });
    ```
    
5.  Create the popup `html` element. Add the element inside your map container.
    
    ```html
    <div id="map">
         <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
         <div id="popup" class="ol-popup">
           <a href="#" id="popup-closer" class="ol-popup-closer"></a>
           <div id="popup-content"></div>
         </div>
       </div>
    ```
    
6.  Create the style for the popup. Add this lines into the `CSS` file
    
    ```css
    .ol-popup {
         position: absolute;
         background-color: white;
         box-shadow: 0 1px 4px rgba(0,0,0,0.2);
         padding: 15px;
         border-radius: 10px;
         border: 1px solid #cccccc;
         bottom: 12px;
         left: -50px;
         min-width: 280px;
       }
       .ol-popup:after, .ol-popup:before {
         top: 100%;
         border: solid transparent;
         content: " ";
         height: 0;
         width: 0;
         position: absolute;
         pointer-events: none;
       }
       .ol-popup:after {
         border-top-color: white;
         border-width: 10px;
         left: 48px;
         margin-left: -10px;
       }
       .ol-popup:before {
         border-top-color: #cccccc;
         border-width: 11px;
         left: 48px;
         margin-left: -11px;
       }
       .ol-popup-closer {
         text-decoration: none;
         position: absolute;
         top: 2px;
         right: 8px;
       }
       .ol-popup-closer:after {
         content: "✖";
       }
    ```
    
7.  Create the overlay to anchor the popup
    
    ```js
    const container = document.getElementById('popup');
     const content = document.getElementById('popup-content');
     const closer = document.getElementById('popup-closer');
     const overlay = new Overlay({
       element: container,
       autoPan: {
         animation: {
           duration: 250,
         },
       },
     });
     closer.onclick = function () {
       overlay.setPosition(undefined);
       closer.blur();
       return false;
     };
    ```
    
8.  Add the overlay to the map
    
    ```js
    const map = new Map({
       layers: [
         new TileLayer({
           source: source
         })
       ],
       overlays: [overlay],
       controls: defaultControls({ attribution: false }).extend([attribution]),
       target: 'map',
       view: new View({
         constrainResolution: true,
         center: fromLonLat([13.39, 52.51]), // starting position [lng, lat]
         zoom: 3 // starting zoom
       })
     });
    ```
    
9.  Create a function to display a popup when clicking on the geojson layer and show the information of the age attribute
    
    ```js
    map.on('click', function (evt) {
       const features = map.getFeaturesAtPixel(evt.pixel);
       const feature = features.length ? features[0] : undefined;
       if (feature.get('age')) {
         const coordinate = evt.coordinate;
         content.innerHTML = `<h3>Average age of </br> women at first marriage</h3><p>${feature.get('age')}</p>`;
         overlay.setPosition(coordinate);
       } else {
         overlay.setPosition(undefined);
       }
     });
    ```
    
10.  Create a map legend. Update your `html` file add this lines after the map container.
     
     ```html
     <div id="state-legend" class="legend">
        <h4>Mean age of </br> women at first marriage </h4>
          <div><span style="background-color: #fff5eb"></span>23</div>
          <div><span style="background-color: #fee6ce"></span>24</div>
          <div><span style="background-color: #fdd0a2"></span>25</div>
          <div><span style="background-color: #fdae6b"></span>26</div>
          <div><span style="background-color: #fd8d3c"></span>27</div>
          <div><span style="background-color: #f16913"></span>28</div>
          <div><span style="background-color: #d94801"></span>29</div>
          <div><span style="background-color: #8c2d04"></span>30</div>
      </div>
      <script>
     ```
     
11.  Create the style for the map legend. Add this code in your `CSS` file.
     
     ```css
     .legend {
        background-color: #000;
        border-radius: 3px;
        bottom: 30px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
        color: #fff ;
        font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
        padding: 10px;
        position: absolute;
        right: 10px;
        z-index: 1;
      }
     
      .legend h4 {
        margin: 0 0 10px;
      }
     
      .legend div span {
        border-radius: 50%;
        display: inline-block;
        height: 10px;
        margin-right: 5px;
        width: 10px;
      }
     ```
     

### Complete source code

```bash
npm install --save ol
```

#### main.js

```js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import TileJSON from 'ol/source/TileJSON.js';
import Style from 'ol/style/Style.js';
import Fill from 'ol/style/Fill.js';
import Stroke from 'ol/style/Stroke.js';
import Attribution from 'ol/control/Attribution.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import Overlay from 'ol/Overlay.js';
import { defaults as defaultControls } from 'ol/control/defaults.js';
import { fromLonLat } from 'ol/proj.js';
import 'ol/ol.css';

const key = 'YOUR_MAPTILER_API_KEY_HERE';

const attribution = new Attribution({
  collapsible: false,
});

const container = document.getElementById('popup');
const content = document.getElementById('popup-content');
const closer = document.getElementById('popup-closer');
const overlay = new Overlay({
  element: container,
  autoPan: {
    animation: {
      duration: 250,
    },
  },
});
closer.onclick = function () {
  overlay.setPosition(undefined);
  closer.blur();
  return false;
};

const source = new TileJSON({
  url: `https://api.maptiler.com/maps/dataviz-v4-dark/tiles.json?key=${key}`,
  tileSize: 512,
  crossOrigin: 'anonymous'
});

const map = new Map({
  layers: [
    new TileLayer({
      source: source
    })
  ],
  overlays: [overlay],
  controls: defaultControls({ attribution: false }).extend([attribution]),
  target: 'map',
  view: new View({
    constrainResolution: true,
    center: fromLonLat([13.39, 52.51]), // starting position [lng, lat]
    zoom: 3 // starting zoom
  })
});

const styles = function (feature, resolution) {
  if (feature.get('age') >= 30) { color = '#8c2d04'; }
  else if (feature.get('age') >= 29) { color = '#d94801'; }
  else if (feature.get('age') >= 28) { color = '#f16913'; }
  else if (feature.get('age') >= 27) { color = '#fd8d3c'; }
  else if (feature.get('age') >= 26) { color = '#fdae6b'; }
  else if (feature.get('age') >= 25) { color = '#fdd0a2'; }
  else if (feature.get('age') >= 24) { color = '#fee6ce'; }
  else { color = '#fff5eb'; }

  return [
    new Style({
      stroke: new Stroke({
        color: 'black',
        width: 0.7,
      }),
      fill: new Fill({
        color: color,
      }),
    }),
  ]
};

const geojson = new VectorLayer({
  source: new VectorSource({
    format: new GeoJSON(),
    url: `https://api.maptiler.com/data/YOUR_CUSTOM_MAP_ID/features.json?key=${key}`,
  }),
  style: styles
});
map.addLayer(geojson);

map.on('click', function (evt) {
  const features = map.getFeaturesAtPixel(evt.pixel);
  const feature = features.length ? features[0] : undefined;
  if (feature && feature.get('age')) {
    const coordinate = evt.coordinate;
    content.innerHTML = `<h3>Average age of </br> women at first marriage</h3><p>${feature.get('age')}</p>`;
    overlay.setPosition(coordinate);
  } else {
    overlay.setPosition(undefined);
  }
});
```

#### index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="robots" content="noindex">
  <title>How to create a choropleth Map from GeoJSON using OpenLayers | NPM example</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div id="map">
    <a href="https://www.maptiler.com" style="position:absolute;left:10px;bottom:10px;z-index:999;"><img
        src="https://api.maptiler.com/resources/logo.svg" alt="MapTiler logo"></a>
    <div id="popup" class="ol-popup">
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content"></div>
    </div>
  </div>
  <div id="state-legend" class="legend">
    <h4>Mean age of </br> women at first marriage </h4>
    <div><span style="background-color: #fff5eb"></span>23</div>
    <div><span style="background-color: #fee6ce"></span>24</div>
    <div><span style="background-color: #fdd0a2"></span>25</div>
    <div><span style="background-color: #fdae6b"></span>26</div>
    <div><span style="background-color: #fd8d3c"></span>27</div>
    <div><span style="background-color: #f16913"></span>28</div>
    <div><span style="background-color: #d94801"></span>29</div>
    <div><span style="background-color: #8c2d04"></span>30</div>
  </div>
  <script type="module" src="./main.js"></script>
</body>
</html>
```

#### style.css

```css
body {
  margin: 0;
  padding: 0;
}

#map {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.ol-popup {
  position: absolute;
  background-color: white;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 280px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
}

.ol-popup-closer:after {
  content: "✖";
}

.legend {
  background-color: #000;
  border-radius: 3px;
  bottom: 30px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  color: #fff;
  font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
  padding: 10px;
  position: absolute;
  right: 10px;
  z-index: 1;
}

.legend h4 {
  margin: 0 0 10px;
}

.legend div span {
  border-radius: 50%;
  display: inline-block;
  height: 10px;
  margin-right: 5px;
  width: 10px;
}
```

## Learn more

Get more details about this tutorial on [Zoomable Choropleth Map from GeoJSON with OpenLayers](https://docs.maptiler.com/openlayers/examples/choropleth-geojson/) or check out the following How-tos related to choropleth maps

[How to style a choropleth map in Edit Tool](https://docs.maptiler.com/sdk-js/examples/countries-with-own-data/)

[Prepare GeoJSON with attributes for choropleth map and upload GeoJSON to MapTiler](https://docs.maptiler.com/guides/maps-apis/maps-platform/prepare-geojson-with-attributes-for-choropleth-map-and-upload-geojson-to-maptiler-cloud)

## Related examples

### [Point GeoJSON Layer](https://docs.maptiler.com/openlayers/examples/geojson-points/)

Tutorials

Add Point GeoJSON data to OpenLayers maps easily.

### [Polygon GeoJSON Layer](https://docs.maptiler.com/openlayers/examples/geojson-polygon/)

Tutorials

Display Polygon GeoJSON data on map using OpenLayers.

### [Vector tiles with GeoJSON](https://docs.maptiler.com/openlayers/examples/vector-tiles-with-polygon-from-geojson/)

Tutorials

Display GeoJSON polygons over vector tiles using OpenLayers.

### [MultiGeom GeoJSON Layer](https://docs.maptiler.com/openlayers/examples/geojson-multigeometry/)

Tutorials

Display MultiGeometry GeoJSON data on map using OpenLayers.
