创建第一个应用
本教程将一步步指导你创建一个完整的 DMap3D 应用,包括创建 3D 地球、配置底图、添加标记和使用 SDK 工具。
前置条件
确保你已经完成了 安装指南 中的步骤,项目已配置好 Cesium 和 DMap3D。
第一步:创建基础场景
React 项目(推荐)
创建一个 React 组件来初始化 3D 地球:
src/App.tsx
import { useEffect, useRef } from 'react'
import * as Cesium from 'cesium'
import 'cesium/Build/Cesium/Widgets/widgets.css'
function App() {
const containerRef = useRef<HTMLDivElement>(null)
const viewerRef = useRef<Cesium.Viewer | null>(null)
useEffect(() => {
if (!containerRef.current || viewerRef.current) return
// 配置 Cesium Ion Token(在 https://ion.cesium.com 注册获取)
Cesium.Ion.defaultAccessToken = 'your-cesium-ion-token'
// 创建 Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
animation: false, // 隐藏动画控件
timeline: false, // 隐藏时间轴
fullscreenButton: false, // 隐藏全屏按钮
geocoder: false, // 隐藏搜索框
homeButton: false, // 隐藏 Home 按钮
sceneModePicker: false, // 隐藏场景模式选择器
selectionIndicator: false, // 隐藏选择指示器
navigationHelpButton: false,
infoBox: false,
baseLayerPicker: false,
})
viewerRef.current = viewer
// 设置初始视角(中国全景)
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(104.0, 35.0, 5000000),
})
return () => {
if (viewerRef.current) {
viewerRef.current.destroy()
viewerRef.current = null
}
}
}, [])
return <div ref={containerRef} style={{ width: '100%', height: '100vh' }} />
}
export default App
原生 HTML 方式
如果不使用框架,可以用纯 HTML:
index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>DMap3D 第一个应用</title>
<script src="https://unpkg.com/cesium/Build/Cesium/Cesium.js"></script>
<link rel="stylesheet" href="https://unpkg.com/cesium/Build/Cesium/Widgets/widgets.css">
<style>
html, body, #cesiumContainer {
width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
}
</style>
</head>
<body>
<div id="cesiumContainer"></div>
<script>
Cesium.Ion.defaultAccessToken = 'your-cesium-ion-token'
const viewer = new Cesium.Viewer('cesiumContainer', {
animation: false,
timeline: false,
baseLayerPicker: false,
})
</script>
</body>
</html>
启动后你将看到一个 3D 地球,可以通过鼠标拖拽旋转、滚轮缩放。
第二步:配置天地图底图
默认底图是 Bing Maps,国内访问较慢。推荐使用天地图(需在 天地图官网 注册获取 Token):
使用天地图底图
const viewer = new Cesium.Viewer(containerRef.current, {
// ... 其他配置
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,
})
),
})
天地图 Token
访问 天地图开发者平台 注册并创建应用,即可获取免费 Token。
第三步:添加地形
加载全球地形可以让地球表面有真实的起伏效果:
加载全球地形
const viewer = new Cesium.Viewer(containerRef.current, {
terrain: Cesium.Terrain.fromWorldTerrain(),
// ... 其他配置
})
或者在创建后动态加载:
viewer.scene.setTerrain(Cesium.Terrain.fromWorldTerrain())
第四步:添加标记点
在地球上添加一些标记点:
添加标记点
// 添加点标记 + 文字标签
viewer.entities.add({
name: '北京',
position: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042),
point: {
pixelSize: 10,
color: Cesium.Color.RED,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
},
label: {
text: '北京',
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -15),
},
})
// 飞到标记点
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 50000),
duration: 2.0,
})
第五步:使用 DMap3D SDK
现在引入 DMap3D,使用测量和绘制工具:
距离测量
添加距离测量功能
import DMap3D from 'dmap3d'
// 创建距离测量工具
const distanceTool = new DMap3D.measurement.spaceDistance(viewer, {
lineColor: '#ffff00',
pointColor: '#ff0000',
fontColor: '#ffffff',
})
// 激活测量(左键添加点,右键结束)
distanceTool.activate()
// 监听测量完成
distanceTool.onMeasureEnd((result) => {
console.log('总距离:', result.totalDistance, '米')
})
多边形绘制
添加绘制功能
// 创建多边形绘制工具
const polygonTool = new DMap3D.drawing.polygon({
viewer,
style: {
fillColor: '#0000FF',
fillAlpha: 0.3,
outlineColor: '#FFFFFF',
outlineWidth: 2,
},
clampToGround: true,
})
// 开始绘制(左键添加顶点,右键完成)
polygonTool.draw((entity, positions) => {
console.log('绘制完成,顶点数:', positions.length)
})
可视域分析
添加可视域分析
// 创建可视域分析工具
const viewshedTool = new DMap3D.analysis.viewshed(viewer, {
visibleLineColor: '#00ff00',
invisibleLineColor: '#ff0000',
})
// 激活分析(点击设置观察点)
viewshedTool.activate()
第六步:完整示例
将以上步骤整合到一个完整的 React 组件中:
src/App.tsx
import { useEffect, useRef, useState } from 'react'
import * as Cesium from 'cesium'
import DMap3D from 'dmap3d'
import 'cesium/Build/Cesium/Widgets/widgets.css'
function App() {
const containerRef = useRef<HTMLDivElement>(null)
const viewerRef = useRef<Cesium.Viewer | null>(null)
const [activeTool, setActiveTool] = useState<string>('')
useEffect(() => {
if (!containerRef.current || viewerRef.current) return
Cesium.Ion.defaultAccessToken = 'your-cesium-ion-token'
const viewer = new Cesium.Viewer(containerRef.current, {
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
selectionIndicator: 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_TOKEN',
layer: 'img',
style: 'default',
tileMatrixSetID: 'w',
format: 'tiles',
maximumLevel: 18,
})
),
terrain: Cesium.Terrain.fromWorldTerrain(),
})
viewerRef.current = viewer
// 添加标记
viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042),
point: { pixelSize: 10, color: Cesium.Color.RED },
label: {
text: '北京',
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -15),
},
})
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(116.4074, 39.9042, 50000),
})
return () => {
viewer.destroy()
viewerRef.current = null
}
}, [])
// 距离测量
const handleMeasureDistance = () => {
const viewer = viewerRef.current
if (!viewer) return
const tool = new DMap3D.measurement.spaceDistance(viewer, {
lineColor: '#ffff00',
pointColor: '#ff0000',
})
tool.activate()
setActiveTool('distance')
}
// 多边形绘制
const handleDrawPolygon = () => {
const viewer = viewerRef.current
if (!viewer) return
const tool = new DMap3D.drawing.polygon({
viewer,
style: { fillColor: '#0000FF', fillAlpha: 0.3 },
clampToGround: true,
})
tool.draw()
setActiveTool('polygon')
}
return (
<div style={{ position: 'relative', width: '100%', height: '100vh' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
<div style={{
position: 'absolute', top: 20, right: 20,
background: 'rgba(0,0,0,0.7)', padding: 16, borderRadius: 8,
color: '#fff',
}}>
<h3 style={{ margin: '0 0 12px 0' }}>工具栏</h3>
<button onClick={handleMeasureDistance} style={btnStyle}>
距离测量
</button>
<button onClick={handleDrawPolygon} style={btnStyle}>
绘制多边形
</button>
{activeTool && <p style={{ marginTop: 8 }}>当前工具: {activeTool}</p>}
</div>
</div>
)
}
const btnStyle: React.CSSProperties = {
display: 'block', width: '100%', padding: '8px 16px',
marginBottom: 8, border: 'none', borderRadius: 4,
background: '#1890ff', color: '#fff', cursor: 'pointer',
}
export default App
运行应用
打开浏览器你将看到:
- 一个带有天地图底图和全球地形的 3D 地球
- 北京位置的红色标记点
- 右上角工具栏,可以进行距离测量和多边形绘制
操作提示
| 操作 | 鼠标 |
|---|---|
| 旋转地球 | 按住左键拖动 |
| 缩放 | 滚轮 |
| 平移 | 按住右键拖动 |
| 倾斜视角 | 按住中键拖动 |
| 测量/绘制 | 左键添加点,右键结束 |
下一步
恭喜你完成了第一个 DMap3D 应用!接下来可以: