效果图
// 随机创建1000个要素
const source = new VectorSource()
for (let i = 1; i <= 200; i++) {
const coordinates = fromLonLat([120.0 + Math.random(), 30.0 + Math.random()])
const feature = new Feature(new Point(coordinates))
source.addFeature(feature)
}
for (let i = 1; i <= 200; i++) {
const coordinates = fromLonLat([120.01 + Math.random(), 30.01 + Math.random()])
const feature = new Feature(new Point(coordinates))
source.addFeature(feature)
}
for (let i = 1; i <= 200; i++) {
const coordinates = fromLonLat([120.02 + Math.random(), 30.02 + Math.random()])
const feature = new Feature(new Point(coordinates))
source.addFeature(feature)
}
for (let i = 1; i <= 200; i++) {
const coordinates = fromLonLat([120.03 + Math.random(), 30.03 + Math.random()])
const feature = new Feature(new Point(coordinates))
source.addFeature(feature)
}
for (let i = 1; i <= 200; i++) {
const coordinates = fromLonLat([120.04 + Math.random(), 30.04 + Math.random()])
const feature = new Feature(new Point(coordinates))
source.addFeature(feature)
}
// 聚合
const cluster = new Cluster({
source,
distance: 100 // 聚合点之间的距离
})
// 创建图层
const layer = new VectorLayer({
source: cluster,
style: function (feature, resolution) {
const size = feature.get('features').length
// 当只有一个点位时 直接展示图片icon
if (size == 1) {
return new Style({
image: new Icon({
src: img,
width: 10,
height: 10
})
})
} else {
return new Style({
image: new StyleCircle({
radius: 20,
stroke: new Stroke({
color: 'white'
}),
fill: new Fill({
color: 'blue'
})
}),
text: new Text({
text: size.toString(),
fill: new Fill({
color: 'white'
})
})
})
}
}
})
window.olMap.addLayer(layer)
当达到地图最大层级 且 还有部分数据成聚合时,需要手动控制全部展开
// 监听地图分辨率改变事件
window.olMap.getView().on('change:resolution', (event) => {
if (window.olMap.getView().getZoom() === window.olMap.getView().getMaxZoom()) {
cluster.setDistance(0)
} else {
cluster.setDistance(100)
}
})
当 size > 1 时 点击Circle 事件
window.olMap.on('singleclick', (e) => {
const pixel = window.olMap.getEventPixel(e.originalEvent)
const currentFeature = window.olMap.forEachFeatureAtPixel(pixel, (feature, layer) => {
return feature
})
if (currentFeature) {
const features = currentFeature.get('features')
if (features.length > 1) {
console.log(`${features.length}个要素`)
}
if (features.length == 1) {
console.log('1个要素')
}
}
})