MapSnippets logoMapSnippets logo

Heatmap Layer with MapLibre GL JS

MapLibre GL JS

Visualize point density using the native heatmap layer type: no plugins needed.

progress_activityLoading map...
const map = new maplibregl.Map({
  container: 'map',
  style: 'https://api.maptiler.com/maps/dataviz-dark/style.json?key=YOUR_MAPTILER_KEY',
  center: [14.42, 50.08],
  zoom: 10
});
const pts = [];
for (let i = 0; i < 500; i++) {
  const a = Math.random() * Math.PI * 2, r = Math.random() * 0.1;
  pts.push({ type: 'Feature', geometry: { type: 'Point', coordinates: [14.42 + Math.cos(a) * r, 50.08 + Math.sin(a) * r] },
    properties: { weight: Math.random() } });
}
map.on('load', () => {
  map.addSource('heat', { type: 'geojson', data: { type: 'FeatureCollection', features: pts } });
  map.addLayer({ id: 'heatmap', type: 'heatmap', source: 'heat', paint: {
    'heatmap-weight': ['get', 'weight'],
    'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 8, 1, 13, 3],
    'heatmap-color': ['interpolate', ['linear'], ['heatmap-density'], 0, 'rgba(33,102,172,0)', 0.2, '#4393c3', 0.4, '#d6604d', 0.6, '#f4a582', 0.8, '#fddbc7', 1, '#fff'],
    'heatmap-radius': ['interpolate', ['linear'], ['zoom'], 8, 10, 13, 25],
    'heatmap-opacity': 0.8
  } });
});

How it works

MapLibre has a built-in heatmap layer type that renders point density visualization on the GPU. No plugins are needed. Points with higher heatmap-weight contribute more to the density calculation.

The heatmap-color expression maps density values (0 to 1) to a color ramp. The heatmap-radius and heatmap-intensity expressions can vary by zoom level: increasing radius at higher zooms keeps the heatmap visually consistent.

This example generates 500 random points clustered around Prague. In production, use real data from a GeoJSON file or API.

Key APIs

API Description Docs
heatmap layer type GPU-rendered density visualization maplibre.org docs
heatmap-weight Per-feature contribution to density maplibre.org docs
heatmap-density Expression returning local density maplibre.org docs

FAQ

How do I adjust the spread of the heatmap?

Increase heatmap-radius for broader spread, or decrease it for more localized hotspots. Use zoom-dependent values for consistent appearance.

Can I combine a heatmap with a point layer?

Yes. Add a circle layer on top of the heatmap and use zoom-dependent opacity to fade between them: show heatmap at low zoom, points at high zoom.

Common mistakes

  • Using a constant heatmap-radius across all zoom levels: the heatmap disappears at high zoom
  • Forgetting heatmap-weight: all points contribute equally, hiding density variation
  • Using heatmap layer type with non-Point geometries: only Point features are supported
auto_awesome

Build maps using MapLibre GL JS with AI

Generate code like this heatmap layer with maplibre gl js example using the MapLibre GL JS skill in your IDE.