MapSnippets logoMapSnippets logo

Heatmap Layer with OpenLayers

OpenLayers

Visualize point density using ol.layer.Heatmap with weighted features on a MapTiler basemap.

progress_activityLoading map...
var features = [];
for (var i = 0; i < 500; i++) {
  var feature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([2.3 + Math.random() * 0.15, 48.83 + Math.random() * 0.06])),
    weight: Math.random()
  });
  features.push(feature);
}
var heatmap = new ol.layer.Heatmap({
  source: new ol.source.Vector({ features: features }),
  blur: 15,
  radius: 10,
  weight: function(feature) { return feature.get('weight'); }
});
var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'https://api.maptiler.com/maps/streets-v4/256/{z}/{x}/{y}.png?key=YOUR_MAPTILER_KEY', attributions: '&copy; <a href="https://www.maptiler.com/copyright/">MapTiler</a>' }) }),
    heatmap
  ],
  view: new ol.View({ center: ol.proj.fromLonLat([2.37, 48.86]), zoom: 13 })
});

How it works

ol.layer.Heatmap renders point features as a density visualization. Each point contributes to the heat intensity based on its weight value (0 to 1).

The blur and radius parameters control the visual spread of each point. Higher blur creates smoother gradients; larger radius extends the influence area. The weight function extracts the weight value from each feature’s properties.

The heatmap automatically updates when zooming: points spread out at lower zoom levels and concentrate at higher zooms.

Key APIs

API Description Docs
ol.layer.Heatmap Heatmap rendering layer openlayers.org
blur Blur size in pixels openlayers.org
radius Point radius in pixels openlayers.org

FAQ

How do I change the heatmap colors?

Use the gradient property with an array of CSS color strings, e.g., ['#00f', '#0ff', '#0f0', '#ff0', '#f00'].

Can I update heatmap data dynamically?

Yes. Add or remove features from the heatmap’s vector source. The visualization updates automatically.

Common mistakes

  • Setting all weights to the same value: this produces a uniform blob with no density contrast
  • Using blur and radius values that are too large, making the entire map a single color
  • Forgetting to return a number from the weight function: it must return a value between 0 and 1
auto_awesome

Build maps using OpenLayers with AI

Generate code like this heatmap layer with openlayers example using the OpenLayers skill in your IDE.