vue3 + openlayers---点位聚合

效果图
在这里插入图片描述

// 随机创建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个要素')
    }
  }
})
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值