Skip to content

Visualize population density

Use a variable binding expression to calculate and display population density.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Visualize population density</title>
    <meta property="og:description" content="Use a variable binding expression to calculate and display population density." />
    <meta charset='utf-8'>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel='stylesheet' href='https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.css' />
    <script src='https://unpkg.com/maplibre-gl@4.7.1/dist/maplibre-gl.js'></script>
    <style>
        body { margin: 0; padding: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body>
<div id="map"></div>
<script>
    const map = new maplibregl.Map({
        container: 'map', // container id
        style:
            'https://api.maptiler.com/maps/streets/style.json?key=get_your_own_OpIi9ZULNHzrESv6T2vL', // stylesheet location
        center: [30.0222, -1.9596], // starting position [lng, lat]
        zoom: 7 // starting zoom
    });

    map.on('load', () => {
        map.addSource('rwanda-provinces', {
            'type': 'geojson',
            'data':
                'https://maplibre.org/maplibre-gl-js/docs/assets/rwanda-provinces.geojson'
        });
        map.addLayer({
            'id': 'rwanda-provinces',
            'type': 'fill',
            'source': 'rwanda-provinces',
            'layout': {},
            'paint': {
                'fill-color': [
                    'let',
                    'density',
                    ['/', ['get', 'population'], ['get', 'sq-km']],
                    [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        8,
                        [
                            'interpolate',
                            ['linear'],
                            ['var', 'density'],
                            274,
                            ['to-color', '#edf8e9'],
                            1551,
                            ['to-color', '#006d2c']
                        ],
                        10,
                        [
                            'interpolate',
                            ['linear'],
                            ['var', 'density'],
                            274,
                            ['to-color', '#eff3ff'],
                            1551,
                            ['to-color', '#08519c']
                        ]
                    ]
                ],
                'fill-opacity': 0.7
            }
        });
    });
</script>
</body>
</html>