Vue+Openlayers实现点要素聚合
在一些场景下(比如地图上的点要素过多,会显得很密集),当我们缩小地图的时候,密集的点会覆盖住地图的信息,显得很杂乱,也会影响地图的渲染,此时,我们便可以使用Cluster对点要素进行聚合。
环境的搭建不再赘述,不懂的可以先看第一篇文章。
首先是需要引入的包:
import Map from 'ol/Map';
import View from 'ol/View';
import Feature from 'ol/Feature';
import VectorSource from 'ol/source/Vector';
import Cluster from 'ol/source/Cluster';
import {Vector as VectorLayer} from 'ol/layer';
实现功能的代码:
/** 添加随机点坐标到地图并实现聚合效果 */
addClusterLayerToMap() {
let coord = undefined;
let feature = undefined;
let coords = [];
for (let i = 0; i < 500; i++) { // 随机生成五百个点并添加至地图
coord = [104.30 + Math.random() * 0.05, 30.06 + Math.random() * 0.05];
feature = new Feature({
geometry: new Point(fromLonLat(coord)),
});
coords.push(feature);
}
const clusterSource = new Cluster({
distance: 10, // 要素将被聚合在一起的像素距离,默认为20
minDistance: 20, // 聚合块之间的最小像素距离,默认为零
source: new VectorSource({
features: coords,
}),
});
const clusters = new VectorLayer({
source: clusterSource,
name: 'clusterLayer',
zIndex: 1,
});
this.map.addLayer(clusters); // 将可聚合的点图层添加至地图
}
最后一行的this.map是我之前就已经初始化好的,若未进行地图的初始化,请先移步:Vue+OpenLayers入门(加载高德在线地图)
以上便是Openlayers如何实现点要素的聚合了。