1. 为什么需要Cesium热力图?
当你在处理地理空间数据时,经常会遇到这样的场景:手上有成百上千个带有经纬度和数值的坐标点,比如气象站的温度数据、共享单车的分布密度、城市人口热力分布等。如果直接在三维地图上用点标记展示,密密麻麻的点会让地图变得杂乱无章,根本看不出数据的分布规律。
这时候热力图就派上用场了。它能将这些离散的点数据转化为连续的色彩渐变区域,用颜色深浅直观展示数据密度和强度。比如在智慧城市项目中,我们经常用热力图来展示人流密度、交通拥堵程度等。红色区域表示高密度,蓝色区域表示低密度,一眼就能看出重点区域在哪里。
传统二维地图的热力图实现已经比较成熟,但放到三维地球场景中就面临几个挑战:
- 如何将平面canvas绘制的热力图贴到三维球体表面
- 经纬度坐标与热力图像素坐标的转换
- 热力图在三维场景中的性能优化
Cesium作为最流行的三维地理可视化引擎,原生并没有提供热力图功能。但通过结合heatmap.js这个专门的热力图库,我们可以完美解决这个问题。下面我就带你从原理到代码,一步步实现这个功能。
2. 核心原理:Canvas转材质贴图
2.1 heatmap.js的工作原理
heatmap.js是一个轻量级的热力图生成库,它的核心原理其实很简单:
- 创建一个canvas画布
- 根据传入的点坐标和值,在canvas上绘制半透明渐变圆点
- 通过模糊和叠加算法生成平滑的热力效果
它的输入数据格式是这样的:
{ x: 100, // 像素x坐标 y: 150, // 像素y坐标 value: 80 // 该点的值 }但我们的地理数据通常是这样的:
{ lnglat: [116.404, 39.915], // 经纬度 value: 80 }2.2 Cesium的材质系统
Cesium支持将图片作为材质贴到各种几何体上。关键方法是:
new Cesium.ImageMaterialProperty({ image: canvas.toDataURL() // 将canvas转为图片URL })所以整体思路就很清晰了:
- 用heatmap.js在canvas上生成热力图
- 将canvas转为图片URL
- 作为材质应用到Cesium的Polygon上
2.3 两种实现方式对比
在实际项目中,通常有两种实现方案:
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| Entity/Polygon材质 | 可随地形起伏,支持3D效果 | 性能较差,数据量大时卡顿 | 小范围高精度展示 |
| ImageryLayer | 性能好,支持大数据量 | 只能平面展示,无法3D | 大范围概览 |
本文主要介绍第一种方式,因为它更灵活,能实现更复杂的三维效果。
3. 关键实现:经纬度到像素坐标的转换
3.1 边界计算算法
要实现热力图的准确定位,首先需要确定热力图覆盖的地理范围。我们通过以下步骤计算边界:
- 遍历所有点,找到最小/最大经纬度
- 将经纬度范围适当扩展(防止边缘被裁剪)
- 计算四个角点的笛卡尔坐标
getBound(positions) { // 计算最小最大经纬度 let minLat = Number.MAX_VALUE, maxLat = Number.MIN_VALUE; let minLng = Number.MAX_VALUE, maxLng = Number.MIN_VALUE; positions.forEach(pos => { const carto = Cesium.Cartographic.fromCartesian(pos); if(carto.longitude < minLng) minLng = carto.longitude; if(carto.longitude > maxLng) maxLng = carto.longitude; if(carto.latitude < minLat) minLat = carto.latitude; if(carto.latitude > maxLat) maxLat = carto.latitude; }); // 扩展边界 const latDiff = maxLat - minLat; const lngDiff = maxLng - minLng; minLat -= latDiff * 0.1; maxLat += latDiff * 0.1; minLng -= lngDiff * 0.1; maxLng += lngDiff * 0.1; // 返回四个角点 return { leftTop: Cesium.Cartesian3.fromDegrees(minLng, maxLat), leftBottom: Cesium.Cartesian3.fromDegrees(minLng, minLat), rightTop: Cesium.Cartesian3.fromDegrees(maxLng, maxLat), rightBottom: Cesium.Cartesian3.fromDegrees(maxLng, minLat) }; }3.2 坐标转换算法
有了边界后,我们需要将每个点的经纬度转换为热力图的像素坐标:
- 计算点在边界矩形内的相对位置
- 将相对位置映射到canvas尺寸
const bound = this.getBound(positions); const width = Cesium.Cartesian3.distance(bound.rightTop, bound.leftTop); const height = Cesium.Cartesian3.distance(bound.leftBottom, bound.leftTop); // 计算x/y轴单位向量 const xAxis = Cesium.Cartesian3.subtract(bound.rightTop, bound.leftTop, new Cesium.Cartesian3()); Cesium.Cartesian3.normalize(xAxis, xAxis); const yAxis = Cesium.Cartesian3.subtract(bound.leftBottom, bound.leftTop, new Cesium.Cartesian3()); Cesium.Cartesian3.normalize(yAxis, yAxis); // 坐标转换 const point = positions[i]; const offset = Cesium.Cartesian3.subtract(point, bound.leftTop, new Cesium.Cartesian3()); const x = Cesium.Cartesian3.dot(offset, xAxis) / width * canvasWidth; const y = Cesium.Cartesian3.dot(offset, yAxis) / height * canvasHeight;这个算法确保了无论地图如何缩放旋转,热力图都能正确对应到地理位置上。
4. 完整实现与性能优化
4.1 Heatmap类的封装
基于上述原理,我们可以封装一个完整的Heatmap类:
class CesiumHeatmap { constructor(viewer, options) { this.viewer = viewer; this.options = options; this.points = options.points || []; this.canvasSize = options.canvasSize || 512; // 初始化heatmap.js this.initHeatmap(); // 创建热力图 this.createHeatmap(); } initHeatmap() { this.container = document.createElement('div'); this.viewer.container.appendChild(this.container); this.heatmap = h337.create({ container: this.container, radius: this.options.radius || 25, maxOpacity: 0.6, minOpacity: 0, blur: 0.8 }); } createHeatmap() { // 计算边界 const bounds = this.calculateBounds(); // 转换坐标 const heatmapData = this.convertToHeatmapData(bounds); // 设置数据 this.heatmap.setData({ max: this.options.maxValue || 100, min: this.options.minValue || 0, data: heatmapData }); // 创建多边形 this.createPolygon(bounds); } // 其他方法同上... }4.2 性能优化技巧
在实际使用中,我总结了几点性能优化经验:
合理设置canvas尺寸:通常512x512就能满足大部分需求,过大会降低性能
数据采样:当点数超过1000时,建议先进行空间网格聚合
动态更新:如果数据需要频繁更新,可以复用同一个Heatmap实例:
update(newPoints) { this.points = newPoints; const bounds = this.calculateBounds(); const heatmapData = this.convertToHeatmapData(bounds); this.heatmap.setData({data: heatmapData}); // 更新多边形材质 this.polygon.polygon.material = new Cesium.ImageMaterialProperty({ image: this.heatmap.getDataURL() }); }- 销毁资源:不再使用时务必清理DOM和Entity
destroy() { this.viewer.entities.remove(this.polygon); this.container.remove(); this.heatmap = null; }4.3 常见问题解决
热力图边缘被裁剪怎么办?
- 适当扩大计算边界范围
- 确保边界扩展系数足够(我通常用0.1-0.2)
热力图显示模糊怎么处理?
- 检查canvas尺寸是否足够
- 调整heatmap.js的radius和blur参数
- 确保材质图片质量:
material: new Cesium.ImageMaterialProperty({ image: canvas.toDataURL('image/png', 1.0) // 最高质量 })数据更新后热力图不刷新?
- 确保调用了heatmap.setData()
- 检查材质是否重新赋值
- 确认Entity的material属性是可变的(避免直接使用字符串URL)
5. 进阶:三维热力图实现
除了二维的热力图,我们还可以实现真正的三维热力图效果。核心思路是:
- 使用Primitive API创建自定义几何体
- 在顶点着色器中处理热力值
- 使用同样的热力图作为纹理贴图
关键代码结构:
const primitive = new Cesium.Primitive({ geometryInstances: new Cesium.GeometryInstance({ geometry: new Cesium.PolygonGeometry({ polygonHierarchy: new Cesium.PolygonHierarchy(positions), extrudedHeight: 1000 // 设置高度 }) }), appearance: new Cesium.MaterialAppearance({ material: new Cesium.Material({ fabric: { type: 'Heatmap3D', uniforms: { heatmapTexture: heatmapCanvas.toDataURL(), minValue: 0, maxValue: 100 }, source: `...自定义着色器代码...` } }) }) });在着色器中,我们可以根据高度和热力值混合颜色,实现立体热力效果。这种三维热力图特别适合展示大气污染、地质勘探等需要高度维度的数据。
6. 实战案例:城市人口热力图
最后通过一个实际案例演示如何使用。假设我们要展示某城市的人口密度:
// 模拟数据 const populationData = []; for(let i=0; i<500; i++) { populationData.push({ lnglat: [ 116.3 + Math.random() * 0.5, // 经度范围 39.8 + Math.random() * 0.4 // 纬度范围 ], value: Math.random() * 100 // 人口密度值 }); } // 创建热力图 const heatmap = new CesiumHeatmap(viewer, { points: populationData, canvasSize: 512, radius: 30, gradient: { '0.1': 'blue', '0.5': 'cyan', '0.7': 'lime', '0.9': 'yellow', '1.0': 'red' } }); // 点击查看数值 viewer.screenSpaceEventHandler.setInputAction(movement => { const picked = viewer.scene.pick(movement.endPosition); if(picked && picked.id === heatmap.polygon) { // 显示当前区域的人口密度 console.log('当前区域人口密度:', picked.properties.density); } }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);这个案例展示了完整的实现流程,包括数据准备、热力图创建和交互处理。你可以根据实际需求调整参数,比如修改渐变颜色、调整半径大小等。