Maplibre GL: Population Heatmap with Geoapify Data

Explore an interactive population heatmap visualization created with Maplibre GL and Geoapify, bringing GeoJSON data to life. Visualize population density within the United States in a dynamic way.

by Geoapify

HTML

<script src="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.js"></script>
<link rel="stylesheet" href="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css">
<div id="my-map"></div>

CSS

body {
      margin: 0;
      padding: 0;
    }

    #my-map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }

JavaScript

// The provided API Key is restricted to JSFiddle. 
// Obtain your API Key at https://myprojects.geoapify.com

const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";

// Bounding Box (bbox) for the United States Geographic Region
const bounds = {
  lat1: 51.069,
  lon1: -128.584,
  lat2: 21.657,
  lon2: -59.590
}

// Create a Mapbox GL Map instance
const map = new maplibregl.Map({
  center: [(bounds.lon1 + bounds.lon2) / 2, (bounds.lat1 + bounds.lat2) / 2],
  zoom: 3, // Set the initial zoom level
  container: 'my-map', // Specify the HTML container where the map will be displayed
  style: `https://maps.geoapify.com/v1/styles/osm-bright-smooth/style.json?apiKey=${myAPIKey}` // Use the specified map style with the provided API key
});

// Add map navigation controls (zoom, pan)
map.addControl(new maplibregl.NavigationControl());

// After the map has loaded
map.on('load', () => {

  // Add a GeoJSON data source for population data
  map.addSource('population', {
    'type': 'geojson',
    'data': 'https://www.geoapify.com/data-share/assets/us-population-data.json'
  });

	// Add a heatmap layer for population data
  // Heatmap Layer style documentation: https://maplibre.org/maplibre-style-spec/layers/#heatmap
  map.addLayer({
      'id': 'population-heat',
      'type': 'heatmap',
      'source': 'population',
      'maxzoom': 9,
      'paint': {
        'heatmap-weight': [
          'interpolate',
          ['linear'],
          ['get', 'population'],
          0,
          0,
          1000,
          0.1,
          10000,
          0.2,
          100000,
          0.3,
          1000000,
          0.5,
          10000000,
          1,
        ],
        'heatmap-intensity': [
          'interpolate',
          ['linear'],
          ['zoom'],
          0,
          1,
          9,
          3
        ],
        'heatmap-color': [
          'interpolate',
          ['linear'],
          ['heatmap-density'],
          0, 'rgba(50, 50, 255, 0)',
          0.2,...