在 Cesium 中生成唯一 ID 有以下几种常见方法,根据使用场景选择最合适的方案:
1. 使用 Cesium 内置的 createGuid()(已弃用但可用)
// Cesium 1.67 之前版本(已弃用但可用)
const id = Cesium.createGuid();
// 示例结果: "b46e8a1a-1a8e-4f5b-9b5b-8a1ab4e8a1b4"
2. 使用浏览器原生 crypto.randomUUID()(推荐,现代浏览器)
// 推荐方案(需现代浏览器支持)
const id = crypto.randomUUID();
// 示例结果: "3d3b1835-5e1b-4d1d-9b7d-af7f5f5d7c5d"
3. 自定义 UUID 生成函数(兼容旧浏览器)
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const id = generateUUID();
// 示例结果: "7c3b1f8a-2e4d-4f7c-9a1d-0b6a8c2d4e1f"
4. 简单唯一字符串(非 UUID 格式)
// 时间戳 + 随机数方案
const id = `id_${Date.now()}_${Math.floor(Math.random() * 1000000)}`;
// 示例结果: "id_1719901234567_384752"
在 Cesium 实体中的典型用法
// 创建带唯一 ID 的实体
const entity = viewer.entities.add({
id: crypto.randomUUID(), // 使用推荐方法
position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
billboard: {
image: "pin.png"
}
});
// 通过 ID 获取实体
const foundEntity = viewer.entities.getById(id);
各方案对比
| 方法 | 优点 | 缺点 |
crypto.randomUUID() |
原生支持、符合 UUID 标准 |
需现代浏览器(IE 不支持) |
Cesium.createGuid() |
内置方法(旧版) |
已弃用(Cesium 1.67+) |
| 自定义 UUID 函数 |
兼容性好 |
随机性不如加密 API |
| 时间戳+随机数 |
简单快速 |
非标准 UUID,可能重复(低概率) |
最佳实践建议
-
现代浏览器项目 → 优先使用 crypto.randomUUID()
-
需要兼容旧浏览器 → 使用自定义 UUID 函数
-
Cesium 旧版本维护 → 临时使用 Cesium.createGuid()(建议升级迁移)
-
非关键简单场景 → 时间戳方案(需确保应用场景无重复风险)
⚠️ 注意:Cesium 1.67+ 已移除 createGuid(),官方推荐使用浏览器原生 API 或第三方 UUID 库(如 uuid)。
参考:https://chat.deepseek.com/a/chat/s/c29e6a18-d434-4023-a247-6ff53098cf06