import 'ol/ol.css';
import Feature from 'ol/Feature';
import Map from 'ol/Map';
import Point from 'ol/geom/Point';
import View from 'ol/View';
import { Circle as CircleStyle, Fill, Stroke, Style, Text, } from 'ol/style';
import {Cluster, OSM, Vector as VectorSource} from 'ol/source';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {boundingExtent} from 'ol/extent';
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));
}
const source = new VectorSource({
features: features,
});
const clusterSource = new Cluster({
distance: parseInt(distanceInput.value, 10),
minDistance: parseInt(minDistanceInput.value, 10),
source: source,
});
this.clusters = new VectorLayer({
source: this.clusterSource,
style: (feature) => {
const size = feature.get('features').length;
if (size === 1) {
// 当缩放到最小层级是可变换为自定义坐标点
return new Style()
} else {
return new Style({
image: new CircleStyle({
radius: 10,
stroke: new Stroke({
color: '#fff'
}),
fill: new Fill({
color: '#3399CC'
})
}),
text: new Text({
text: size.toString(),
fill: new Fill({
color: '#fff'
})
})
});
}
}
});
// 加载默认图层
const raster = new TileLayer({
source: new OSM(),
});
// 初始化地图
const map = new Map({
layers: [raster, clusters],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
// 海量坐标点的点击事件
map.on('click', (e) => {
clusters.getFeatures(e.pixel).then((clickedFeatures) => {
if (clickedFeatures.length) {
// Get clustered Coordinates
const features = clickedFeatures[0].get('features');
if (features.length > 1) {
const extent = boundingExtent(
features.map((r) => r.getGeometry().getCoordinates())
);
map.getView().fit(extent, {duration: 1000, padding: [50, 50, 50, 50]});
} else {
// 点击最小层级的标点,可实现自己的业务
}
}
});
});