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.
-
Copy the following code, paste it into your favorite text editor, and save it as a
.htmlfile.
Check out the step-by-step tutorial How to use OpenLayers
-
Replace
YOUR_MAPTILER_API_KEY_HEREwith your own API key. Make sure to secure the key before you publish it. -
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 thestarting zoom) to match your users’ needs. Additionally, you can change the map’s look (by updating thesource URL); choose from a range of visually appealing map styles from our extensive MapTiler standard maps, or create your own to truly differentiate your application.
-
Add the GeoJSON layer. The following snippet creates GeoJSON layer hosted on MapTiler (check out the How to Upload GeoJSON to MapTiler 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
-
Create the functions to get the style based on the age attribute.
-
Create a choropleth map based on the age attribute. Change the
styleproperty of the layer. -
Create the popup
htmlelement. -
Create the style for the popup
-
Create the overlay to anchor the popup
-
Add the overlay to the map
-
Create a function to display a popup when clicking on the geojson layer and show the information of the age attribute
-
Create a map legend.
-
Create the style for the map legend.
<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>
-
Import the new modules needed to add the new functionality.
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'; -
Add the GeoJSON layer. The following snippet creates GeoJSON layer hosted on MapTiler (check out the How to Upload GeoJSON to MapTiler 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
-
Create the functions to get the style based on the age attribute.
-
Create a choropleth map based on the age attribute. Change the
styleproperty of the layer. -
Create the popup
htmlelement. Add the element inside your map container. -
Create the style for the popup. Add this lines into the
CSSfile -
Create the overlay to anchor the popup
-
Add the overlay to the map
-
Create a function to display a popup when clicking on the geojson layer and show the information of the age attribute
-
Create a map legend. Update your
htmlfile add this lines after the map container. -
Create the style for the map legend. Add this code in your
CSSfile.
npm install --save ol
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);
}
});
<!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>
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 or check out 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