一、什么是聚合
聚合是一种将一定范围内的多个图形合并为一个图形的一种技术方案。通常用来解决图形过于集中或者图形数量过多的问题。
在Openlayers中主要通过Cluster数据源来实现聚合的效果。与其它的数据源不同,Cluster数据源在实例化时需要接收一个矢量数据源作为参数,然后在将Cluster数据源作为一个矢量图层的数据源,这样就能实现对矢量数据源中图形的聚合。

二、如何实现聚合
1.点聚合
如果是有一些点要素需要全部进行聚合,像这种情况实现起来就非常简单,只需要通过distance属性(以像素为单位)设置好聚合的范围就可以了。
// 矢量数据源
const weatherStationSource = new VectorSource({
format: new GeoJSON(),
url: "src/data/气象站点/stations-wgs.geojson",
});
// 聚合数据源
const clusterSource = new Cluster({
distance: 40,
source: weatherStationSource,
});
const weatherStationLayer = new VectorLayer({
properties: {
name: "气象站点",
id: "weather-station",
},
source: clusterSource,
});
window.map.addLayer(weatherStationLayer);
聚合前:

聚合后:

2.部分图形聚合
有的时候我们并不希望将矢量数据源中的所有图形都参与聚合,这个时候可以通过geometryFunction属性进行设置。
geometryFunction属性是一个函数,该函数以一个要素(Feature)作为参数,并返回一个点(Point),以此作为该要素用于聚合计算的点。当某个要素不应被纳入聚类考虑范围时,该函数应返回null。
注意,如果返回null就相当于矢量数据源中没有这个图形。
// 矢量数据源
const weatherStationSource = new VectorSource({
format: new GeoJSON(),
url: "src/data/气象站点/stations-wgs.geojson",
});
// 聚合数据源
const clusterSource = new Cluster({
distance: 40,
source: weatherStationSource,
geometryFunction: function (feature) {
const type = feature.get("type");
console.log(type);
if (type == "基本站") {
return null;
}
return feature.getGeometry();
},
});
const weatherStationLayer = new VectorLayer({
properties: {
name: "气象站点",
id: "weather-station",
},
source: clusterSource,
});
window.map.addLayer(weatherStationLayer);
3.其它图形的聚合
如果需要进行聚

5321

被折叠的 条评论
为什么被折叠?



