官网demo地址:
这篇讲的是如何使用聚合处理大量点数据。
为什么会用聚合呢?当我们在地图上加载了大量矢量点位数据之后,地图就会卡顿,而在地图层级缩放层级较小的时候根本也看不见点位的具体信息。这时候,使用聚合就是一个比较好的解决方案。地图缩小的时候它会将紧挨着的许多点位合并成一个矢量点,放大到一定程度才会显示具体点位信息。
首先,来生成一些点位坐标数组
const count = 20000;
const features = new Array(count);
const e = 4500000;
for (let i = 0; i < count; ++i) {
const coordinates = [
2 * e * Math.random() - e,
2 * e * Math.random() - e,
];
features[i] = new Feature(new Point(coordinates));
}
此时,features里面就是两万个点位的feature。然后把它们加载到矢量数据源上
const source = new VectorSource({
features: features,
});
接着创建聚合类,Cluster的source是一个矢量数据源。distance表示的是feature与feature之间的距离,因为这个示例中有一个滑块动态设置间距,所以这里要设置一下minDistance最小距离。
const clusterSource = new Cluster({
distance: this.distanceInput,
minDistance: this.minDistanceInput,
source: source,
});
然后把source加载图层上。
this.clusterLayer = new VectorLayer({
source: clusterSource,
});
来看下效果:
点位都出来了,接下来加点样式配置。在实例化VectorLayer时加一个style配置,函数里会返回每一个feature,每一个feature上都有一个features属性,记录着它的下级features数组,聚合的原理就是把几个相邻的点通过计算合成一个feature,我猜features里面记录的就是合成这个feature所用的数组。style后面的这个函数是个高频触发的函数,地图稍微移动一下都会触发,所以这里的使用styleCache对象做了缓存效果,以每个feature的features数组的长度作为key,这样就不用每次都重新new Style了。
const styleCache = {};
this.clusterLayer = new VectorLayer({
source: clusterSource,
style: function (feature) {
const size = feature.get("fe