Atlaslog
Atlaslog / Examples / OpenLayers / Cluster
OpenLayers · Runnable Example

Cluster

Cluster 300 points by distance, split them on zoom, and keep the labels readable.

Open standalone → Chinese notes All OpenLayers examples
/demos/openlayers-cluster.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/openlayers-cluster.html
<!--
  示例:点聚合
  要点:ol.source.Cluster 按屏幕距离合并要素,聚合样式读取 features 数量
  依赖:OpenLayers 10.3.1 · jsDelivr CDN
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>点聚合</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@10.3.1/ol.css">
<style>
  html,body{height:100%;margin:0}
  body{display:flex;flex-direction:column;overflow:hidden;
       font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
  .bar{flex:0 0 auto;padding:8px 12px;background:#f6f7f9;border-bottom:1px solid #e3e6ea;
       display:flex;gap:16px;align-items:center;font-size:12px;color:#58606e;flex-wrap:wrap}
  .bar label{display:flex;gap:6px;align-items:center}
  .bar input[type=range]{width:130px}
  #map{flex:1 1 auto;min-height:0;background:#eef0f3}
</style>
</head>
<body>
<div class="bar">
  <label>聚合距离 <input type="range" id="dist" min="20" max="100" step="5" value="45">
    <b id="distVal">45</b> px</label>
  <span>300 个点,单击聚合圆可放大查看</span>
</div>
<div id="map"></div>
<script src="https://cdn.jsdelivr.net/npm/ol@10.3.1/dist/ol.js"></script>
<script>
(function () {
  'use strict';

  if (typeof ol === 'undefined') {
    document.getElementById('map').innerHTML =
      '<div style="padding:20px;color:#b42318">OpenLayers 加载失败,请检查能否访问 cdn.jsdelivr.net</div>';
    return;
  }

  var fromLonLat = ol.proj.fromLonLat;
  var features = [];
  var i;

  for (i = 0; i < 300; i++) {
    var lon = 116.22 + Math.random() * 0.42;
    var lat = 39.82 + Math.random() * 0.20;
    features.push(new ol.Feature({
      geometry: new ol.geom.Point(fromLonLat([lon, lat])),
      code: 'P' + i
    }));
  }

  var clusterSource = new ol.source.Cluster({
    distance: 45,
    minDistance: 20,
    source: new ol.source.Vector({ features: features })
  });

  var clusterLayer = new ol.layer.Vector({
    source: clusterSource,
    style: function (feature) {
      var size = feature.get('features').length;
      var radius = size === 1 ? 5 : Math.min(24, 8 + Math.sqrt(size) * 3);
      var color = size > 40 ? '#b8241c' : (size > 12 ? '#e2672a' : '#1f5fd0');

      if (size === 1) {
        return new ol.style.Style({
          image: new ol.style.Circle({
            radius: radius,
            fill: new ol.style.Fill({ color: '#1f5fd0' }),
            stroke: new ol.style.Stroke({ color: '#ffffff', width: 2 })
          })
        });
      }

      return new ol.style.Style({
        image: new ol.style.Circle({
          radius: radius,
          fill: new ol.style.Fill({ color: color }),
          stroke: new ol.style.Stroke({ color: 'rgba(255,255,255,0.85)', width: 2 })
        }),
        text: new ol.style.Text({
          text: String(size),
          font: '600 12px sans-serif',
          fill: new ol.style.Fill({ color: '#ffffff' })
        })
      });
    }
  });

  var map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({ source: new ol.source.XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}', attributions: 'Tiles © Esri'}) }),
      clusterLayer
    ],
    view: new ol.View({
      center: fromLonLat([116.430, 39.920]),
      zoom: 11
    })
  });

  /* 点击聚合圆:包含多个点时缩放到这些点的范围 */
  map.on('click', function (evt) {
    var hit = null;

    map.forEachFeatureAtPixel(evt.pixel, function (feature) {
      hit = feature;
      return true;
    }, { hitTolerance: 4 });

    if (!hit) return;

    var members = hit.get('features');

    if (!members || members.length < 2) return;

    var extent = ol.extent.createEmpty();
    members.forEach(function (f) {
      ol.extent.extend(extent, f.getGeometry().getExtent());
    });

    map.getView().fit(extent, {
      padding: [60, 60, 60, 60],
      duration: 400,
      maxZoom: 17
    });
  });

  document.getElementById('dist').addEventListener('input', function () {
    clusterSource.setDistance(Number(this.value));
    document.getElementById('distVal').textContent = this.value;
  });
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.

More OpenLayers examples

OpenLayers · EXAMPLECluster Graded OpenLayers · EXAMPLEClusters Dynamic OpenLayers · EXAMPLECog