JavaScript is required
Blog About

Cesium简单点聚合+点击事件

2024/05/07
5 mins read
See this issue
# 开发实践
Back

记录一下遇到的cesium点聚合优化需求

// 生成点标记
generateEntity(id, x, y) {
  if (!x || !y) return

  const handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
  handler.setInputAction((movement) => {
    let position = {
      x: movement.position.x,
      y: movement.position.y
    }
    let pick = this.viewer.scene.pick(position)
    if (Cesium.defined(pick) && pick.id.id == id) {
		// 处理逻辑
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

  const coordinateList = BD09II2WGS84New(x, y);
  return new Cesium.Entity({
    id,
    position: Cesium.Cartesian3.fromDegrees(coordinateList[0], coordinateList[1], 10),
    billboard: {
      image: require('../../assets/img/marker-icon.png'),
      width: 20, //指定该图片或图标的宽度
      height: 33, //指定该图片或图标的高度
      horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
      verticalOrigin: Cesium.VerticalOrigin.TOP,
      pixelOffset: new Cesium.Cartesian2(0, 10),
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 60000),
    },
    label: {
      text: id,
      font: 'normal small-caps normal 14px 黑体',
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      fillColor: Cesium.Color.fromCssColorString("#ffffff"),
      showBackground: false,
      backgroundColor: Cesium.Color(11, 38, 90, 0.5),
      pixelOffset: new Cesium.Cartesian2(0, 0),
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 60000),
    }
  })
}

// 设置点聚合
initCluster() {
  this.viewer.entities.removeAll()
  const dataSource = new Cesium.CustomDataSource("dataSource1"); //自定义一个名为dataSource1的空数据集
  this.dataList.forEach(item => {
    dataSource.entities.add(this.generateEntity(item.name, item.X, item.Y))
  })
  this.viewer.dataSources.add(dataSource).then((dataSource) => {
    dataSource.clustering.enabled = true; //聚合开启
    dataSource.clustering.pixelRange = 20; //设置像素范围,以扩展显示边框
    dataSource.clustering.minimumClusterSize = 5; //设置最小的聚合点数目,超过此数目才能聚合
  })
  dataSource.clustering.clusterEvent.addEventListener(
    function (clusteredEntities, cluster) {
      // 关闭自带的显示聚合数量的标签
      cluster.label.show = false;
      cluster.billboard.show = true;
      cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;

      // 设置聚合图标和大小
      cluster.billboard.image = require('../../assets/img/marker-icon.png');
      cluster.billboard.width = 20;
      cluster.billboard.height = 33;
    }
  )
}