Skip to content

概述

GeoJSON 是 Cesium 中最常用的矢量数据格式之一,常用于描述 点、线、面、属性、样式 等信息。
Cesium 通过 GeoJsonDataSource 对其进行解析并以 实体(Entity) 的形式呈现。

javascript
import shanghai from './assets/shanghai.json'

const dataSource = await Cesium.GeoJsonDataSource.load(shanghai, {
  clampToGround: false,
  stroke: Cesium.Color.BLUE,
  fill: Cesium.Color.ORANGE.withAlpha(0.5),
  strokeWidth: 10, // WebGL(尤其是 WebGL1.0,Cesium 默认支持)在大多数平台上 只支持线宽 = 1 像素。
})
viewer.dataSources.add(dataSource)

dataSource.entities.values.forEach((entity) => {
  const center = entity.properties.centroid?.getValue() || entity.properties.center?.getValue()
  entity.position = Cesium.Cartesian3.fromDegrees(center[0], center[1], center[2] || 0)
  entity.label = new Cesium.LabelGraphics({
    text: entity.name,
    font: '16px sans-serif',
    fillColor: Cesium.Color.WHITE,
    disableDepthTestDistance: Number.POSITIVE_INFINITY,  // 禁用深度测试,文字永远在最前面
    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 500000.0),
  })
})

const handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas)
handler.setInputAction(function (e) {
  const pick = viewer.scene.pick(e.position)
  if ( Cesium.defined(pick) && pick.id && pick.id.polygon ) {
    pick.id.polygon.material = Cesium.Color.RED.withAlpha(0.5)
  }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK)

viewer.zoomTo(dataSource.entities).then(() => {
  viewer.camera.zoomOut(10000)
})
/