首页 / OpenLayers / API 文档
ClusterSource
先看结论
聚合数据源。把屏幕距离相近的要素合并成一个聚合要素,随缩放实时重组。
new ol.source.Cluster(options)
构造参数
| 参数 | 说明 |
|---|---|
source | 底层矢量数据源,必填 |
distance | 聚合距离像素,默认 20,0 表示不聚合 |
minDistance | 两个聚合之间的最小间距像素,默认 0 |
geometryFunction | 取聚合中心点几何的函数,默认取第一个成员的点 |
createCluster | 自定义聚合要素工厂,返回值为聚合要素 |
wrapX | 是否横向循环,默认 true |
常用方法
| 方法 | 返回 | 说明 |
|---|---|---|
getDistance() | number | 取当前聚合距离 |
setDistance(distance) | void | 改聚合距离并立即重组 |
getSource() | VectorSource | 取底层数据源 |
getFeatures() | Array<Feature> | 取当前层级下的聚合要素 |
refresh() | void | 强制重新聚合 |
var cluster = new ol.source.Cluster({
distance: 40,
source: new ol.source.Vector({ features: points })
});
var layer = new ol.layer.Vector({
source: cluster,
style: function (feature) {
var members = feature.get('features');
var size = members.length;
return new ol.style.Style({
image: new ol.style.Circle({
radius: 8 + Math.min(size, 40) * 0.5,
fill: new ol.style.Fill({
color: size > 20 ? '#c0392b' : '#1f5fd0'
}),
stroke: new ol.style.Stroke({ color: '#fff', width: 2 })
}),
text: new ol.style.Text({
text: String(size),
fill: new ol.style.Fill({ color: '#fff' })
})
});
}
});
map.addLayer(layer);
cluster.setDistance(60);
注意事项
- 聚合要素的成员取自
feature.get('features'),未聚合时也会返回长度为 1 的数组,不要直接当单要素处理。 - 聚合要素本身没有业务属性,取值要遍历成员,或通过
createCluster提前汇总。 distance是屏幕像素,缩放时聚合结果会自动重组,因此要素数量在交互过程中会变化。- 对聚合结果做点击查询时,应先把成员展开再弹窗,否则只拿到聚合要素的空属性。
经纬志(2026)。《ClusterSource》。https://www.jingweizhi.com/openlayers/api/cluster-source.html(访问日期 2026-11-03)。