Hello World
这个示例演示如何使用 DMap3D SDK 创建一个基础的 3D 地球场景。
效果预览
创建一个带有天地图底图的 3D 地球,初始视角定位到北京。
完整代码
src/components/HelloWorld.tsx
import { useEffect, useRef } from 'react'
import * as Cesium from 'cesium'
import './HelloWorld.css'
function HelloWorld() {
const containerRef = useRef<HTMLDivElement>(null)
const viewerRef = useRef<Cesium.Viewer | null>(null)
useEffect(() => {
if (!containerRef.current) return
// 设置 Ion Token
Cesium.Ion.defaultAccessToken = 'your-cesium-ion-token'
// 创建 Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
animation: false, // 隐藏动画控件
fullscreenButton: false, // 隐藏全屏按钮
geocoder: false, // 隐藏地理编码搜索
homeButton: false, // 隐藏 Home 按钮
sceneModePicker: false, // 隐藏场景模式选择器
selectionIndicator: false, // 隐藏选择指示器
timeline: false, // 隐藏时间轴
navigationHelpButton: false,
infoBox: false,
baseLayerPicker: false,
// 使用天地图底图
baseLayer: Cesium.ImageryLayer.fromProviderAsync(
new Cesium.WebMapTileServiceImageryProvider({
url: 'https://t0.tianditu.gov.cn/img_w/wmts?tk=YOUR_TIANDITU_TOKEN',
layer: 'img',
style: 'default',
tileMatrixSetID: 'w',
format: 'tiles',
maximumLevel: 18,
})
),
terrainProvider: new Cesium.EllipsoidTerrainProvider({}),
})
viewerRef.current = viewer
// 设置初始视角(北京)
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 1000000.0),
})
return () => {
viewer.destroy()
}
}, [])
return (
<div className="hello-world">
<div ref={containerRef} className="cesium-container" />
</div>
)
}
export default HelloWorld
样式文件
src/components/HelloWorld.css
.hello-world {
position: relative;
width: 100%;
height: 100vh;
}
.cesium-container {
width: 100%;
height: 100%;
}
关键代码说明
1. 设置 Ion Token
Cesium.Ion.defaultAccessToken = 'your-cesium-ion-token'
Cesium Ion 提供地形、影像等在线数据服务,需要在 Cesium Ion 注册获取 Token。
2. 创建 Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
animation: false, // 关闭不需要的 UI 组件
timeline: false,
baseLayerPicker: false,
// ...
})
Viewer 是 Cesium 的核心类,负责渲染 3D 场景。通过配置项可以控制显示哪些 UI 组件。
3. 使用天地图底图
baseLayer: Cesium.ImageryLayer.fromProviderAsync(
new Cesium.WebMapTileServiceImageryProvider({
url: 'https://t0.tianditu.gov.cn/img_w/wmts?tk=YOUR_TOKEN',
layer: 'img',
style: 'default',
tileMatrixSetID: 'w',
format: 'tiles',
maximumLevel: 18,
})
)
使用天地图 WMTS 服务作为底图,需在天地图官网注册获取 Token。
4. 设置初始视角
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 1000000.0),
})
通过经纬度和高度(米)定位相机初始位置。这里定位到北京上空 1000 公里处。
扩展功能
- 切换底图 - 使用不同的影像服务(天地图矢量、卫星、标注图层)
- 添加地形 - 使用
Cesium.Terrain.fromWorldTerrain()加载全球地形 - 场景模式切换 - 支持 2D、2.5D、3D 视图切换
- 自定义 UI - 在 Viewer 上叠加自定义控制面板