相关类方法
ol/source/Cluster
主要参数 options
- distance 要素将聚集在一起的距离(以像素为单位)
- minDistance 簇之间的最小距离(以像素为单位)。不能大于配置的距离。
- source 矢量数据源
通过 let size=features.get("features").length 判断聚合点的大小设置不同的样式
创建点数据
for(let i=0;i<100;i++){
let feature=new Feature(new Point(fromLonLat([200 * Math.random(),300*Math.random()])))
features.push(feature)
}
//数量数据源
let source=new VectorSource({
features:features
})
// 实例化聚合数据源 并设置 聚合距离
let ClusterLayer=new VectorLayer({
source:new Cluster({
source:source,
distance:100,
}),
style:features=>{
let size=features.get("features").length
if(size<3){
return new Style({
image:new Circle({
radius: 10,
stroke: new Stroke({
color: '#fff'
}),
fill: new Fill({
color: '#3399cc'
})
}),
text: new Text({
text: size.toString(), // 以聚合点的数量作为显示的内容
fill: new Fill({
color: '#fff'
}),
offsetY:0.6
})
})
}else{
return new Style({
image:new Circle({
radius: 10,
stroke: new Stroke({
color: '#fff'
}),
fill: new Fill({
color: '#000'
})
}),
text: new Text({
text: size.toString(), // 以聚合点的数量作为显示的内容
fill: new Fill({
color: '#fff',
}),
offsetY:0.6
})
})
}
}
})
完整代码
<script lang="js" setup>
import { Feature, Map, View } from 'ol';
import { Cluster, XYZ } from 'ol/source';
import { onMounted } from 'vue';
import { fromLonLat } from 'ol/proj';
import TileLayer from 'ol/layer/Tile';
import mapData from "../Data/中华人民共和国.json"
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { Point } from 'ol/geom';
import { Fill, Stroke, Style,Circle,Text } from 'ol/style';
let mapIns=null
const initMap=()=>{
mapIns=new Map({
layers:[new TileLayer({
source:new XYZ({
url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=tk",
projection: "EPSG:3857",
}),
name:"map1"
})],
view:new View({
center:fromLonLat([116.403963, 39.915119]),
zoom:3
}),
target:'map'
})
let features=[]
for(let i=0;i<100;i++){
let feature=new Feature(new Point(fromLonLat([200 * Math.random(),300*Math.random()])))
features.push(feature)
}
let source=new VectorSource({
features:features
})
let ClusterLayer=new VectorLayer({
source:new Cluster({
source:source,
distance:100,
}),
style:features=>{
let size=features.get("features").length
if(size<3){
return new Style({
image:new Circle({
radius: 10,
stroke: new Stroke({
color: '#fff'
}),
fill: new Fill({
color: '#3399cc'
})
}),
text: new Text({
text: size.toString(), // 以聚合点的数量作为显示的内容
fill: new Fill({
color: '#fff'
}),
offsetY:0.6
})
})
}else{
return new Style({
image:new Circle({
radius: 10,
stroke: new Stroke({
color: '#fff'
}),
fill: new Fill({
color: '#000'
})
}),
text: new Text({
text: size.toString(), // 以聚合点的数量作为显示的内容
fill: new Fill({
color: '#fff',
}),
offsetY:0.6
})
})
}
}
})
mapIns.addLayer(ClusterLayer)
}
onMounted(()=>{
initMap()
})
</script>
<template>
<div class="container">
<div id="map"></div>
</div>
</template>
<style lang="scss" scoped>
.container {
height: 100%;
#map {
height: 100%;
}
}
</style>