阅读视图

发现新文章,点击刷新页面。

别再瞎写 Cesium 可视化!热力图 + 四色图源码全公开,项目直接复用!

之前 Cesium 中一直围绕着园区进行开发,现在增加地图的部分,后面还会增加公共组件、统计图等等操作。

智慧园区、区域管控等三维GIS场景中,热力图四色图是两大最常用的可视化展示方案。

image.png

热力图直观展示密度、热度、强度分布,四色图清晰区分行政区域、功能分区、风险等级,两者搭配能让三维可视化效果和实用性直接拉满!

热力图

使用 Cesium 纯原生实现,无第三方依赖。

采用多级渐变色的效果,径向渐变过渡显得更加自然。

image.png

同时支持显示/隐藏切换,内存自动释放。

完整代码

const createHeatMap = () => {
    if (heatMapRef.value) {
        cesiumViewer.value.scene.primitives.remove(heatMapRef.value);
        heatMapRef.value = null;
    }
    
    // 热力图数据点(经纬度+权重值)
    const cameraList = [
        { longitude: 117.105914, latitude: 36.437846, height: 15 },
        { longitude: 117.105842, latitude: 36.437532, height: 14 },
        // 此处可替换为你的业务数据...
    ];
    
    // 创建Billboard集合
    const billboardCollection = new Cesium.BillboardCollection({
        scene: cesiumViewer.value.scene
    });
    
    // 计算最大权重,用于归一化
    const maxHeight = Math.max(...cameraList.map(c => c.height));
    
    // 热力图8级渐变色配置
    const heatColors = {
        veryLow: new Cesium.Color(0.0, 0.0, 1.0, 0.2),    // 深蓝
        low: new Cesium.Color(0.0, 0.5, 1.0, 0.3),        // 蓝色
        mediumLow: new Cesium.Color(0.0, 1.0, 1.0, 0.4),  // 青色
        medium: new Cesium.Color(0.5, 1.0, 0.5, 0.5),     // 黄绿色
        mediumHigh: new Cesium.Color(1.0, 1.0, 0.0, 0.6), // 黄色
        high: new Cesium.Color(1.0, 0.7, 0.0, 0.7),       // 橙色
        veryHigh: new Cesium.Color(1.0, 0.3, 0.0, 0.8),   // 橙红
        extreme: new Cesium.Color(1.0, 0.0, 0.0, 0.9)     // 红色
    };
    
    // 遍历数据生成热力点
    cameraList.forEach(camera => {
        const normalizedHeight = camera.height / maxHeight;
        let color, radius, alpha;
        
        // 8级密度分级,自动匹配颜色、半径、透明度
        if (normalizedHeight < 0.125) {
            color = heatColors.veryLow; radius = 40; alpha = 0.25;
        } else if (normalizedHeight < 0.25) {
            const intensity = (normalizedHeight - 0.125) / 0.125;
            color = Cesium.Color.fromBytes(0, Math.round(128 * intensity), 255, Math.round(255 * 0.3));
            radius = 40 + intensity * 15; alpha = 0.3;
        } else if (normalizedHeight < 0.375) {
            const intensity = (normalizedHeight - 0.25) / 0.125;
            color = Cesium.Color.fromBytes(0, 128 + Math.round(127 * intensity), 255 - Math.round(127 * intensity), Math.round(255 * 0.35));
            radius = 55 + intensity * 15; alpha = 0.35;
        } else if (normalizedHeight < 0.5) {
            const intensity = (normalizedHeight - 0.375) / 0.125;
            color = Cesium.Color.fromBytes(Math.round(128 * intensity), 255, 128 - Math.round(128 * intensity), Math.round(255 * 0.4));
            radius = 70 + intensity * 20; alpha = 0.4;
        } else if (normalizedHeight < 0.625) {
            const intensity = (normalizedHeight - 0.5) / 0.125;
            color = Cesium.Color.fromBytes(128 + Math.round(127 * intensity), 255, 0, Math.round(255 * 0.5));
            radius = 90 + intensity * 25; alpha = 0.5;
        } else if (normalizedHeight < 0.75) {
            const intensity = (normalizedHeight - 0.625) / 0.125;
            color = Cesium.Color.fromBytes(255, 255 - Math.round(178 * intensity), 0, Math.round(255 * 0.6));
            radius = 115 + intensity * 30; alpha = 0.6;
        } else if (normalizedHeight < 0.875) {
            const intensity = (normalizedHeight - 0.75) / 0.125;
            color = Cesium.Color.fromBytes(255, 77 - Math.round(77 * intensity), 0, Math.round(255 * 0.7));
            radius = 145 + intensity * 35; alpha = 0.7;
        } else {
            const intensity = (normalizedHeight - 0.875) / 0.125;
            color = Cesium.Color.fromBytes(255, 0, 0, Math.round(255 * 0.8));
            radius = 180 + intensity * 40; alpha = 0.8;
        }
        
        // 多层圆形叠加,实现渐变光晕效果
        const numCircles = 3;
        for (let i = 0; i < numCircles; i++) {
            const circleRadius = radius * (0.7 + i * 0.15);
            const circleAlpha = alpha * (0.8 - i * 0.2);
            
            // Canvas绘制径向渐变圆形
            const canvas = document.createElement('canvas');
            canvas.width = 256; canvas.height = 256;
            const context = canvas.getContext('2d');
            const gradient = context.createRadialGradient(128,128,0,128,128,128);
            
            gradient.addColorStop(0, `rgba(${Math.round(color.red * 255)}, ${Math.round(color.green * 255)}, ${Math.round(color.blue * 255)}, ${circleAlpha})`);
            gradient.addColorStop(0.7, `rgba(${Math.round(color.red * 255)}, ${Math.round(color.green * 255)}, ${Math.round(color.blue * 255)}, ${circleAlpha * 0.5})`);
            gradient.addColorStop(1, `rgba(${Math.round(color.red * 255)}, ${Math.round(color.green * 255)}, ${Math.round(color.blue * 255)}, 0)`);
            
            context.fillStyle = gradient;
            context.beginPath();
            context.arc(128,128,128,0,Math.PI*2);
            context.fill();
            
            // 添加到场景
            billboardCollection.add({
                position: Cesium.Cartesian3.fromDegrees(camera.longitude, camera.latitude, camera.height),
                image: canvas,
                width: circleRadius * 2,
                height: circleRadius * 2,
                scaleByDistance: new Cesium.NearFarScalar(100,1.0,1000,0.5),
                translucencyByDistance: new Cesium.NearFarScalar(100,1.0,500,0.3),
            });
        }
    });
    
    cesiumViewer.value.scene.primitives.add(billboardCollection);
    heatMapRef.value = billboardCollection;
    cesiumViewer.value.scene.requestRender();
    console.log('✅ 热力图创建成功');
};

加载GeoJson四色图实现

使用 fetch 加载标准GeoJson行政区划/面数据,数据可以从这个地址下载: datav.aliyun.com/portal/scho…

image.png

这里采用的是四色循环渲染,如果想要多种颜色也是一样的。

完整代码

const createColorMap = () => {
    // 已存在则先移除
    if (colorMapRef.value) {
        cesiumViewer.value.dataSources.remove(colorMapRef.value);
        colorMapRef.value = null;
    }
    
    // 加载GeoJson区域数据
    fetch('/json/济南市.geojson')
        .then(res => res.json())
        .then(geojsonData => {
            // 四色图配色
            const colorMap = [
                new Cesium.Color(0.0, 0.0, 1.0, 0.7),   // 蓝
                new Cesium.Color(0.0, 1.0, 0.0, 0.7),   // 绿
                new Cesium.Color(1.0, 1.0, 0.0, 0.7),   // 黄
                new Cesium.Color(1.0, 0.0, 0.0, 0.7),   // 红
            ];
            
            const dataSource = new Cesium.GeoJsonDataSource();
            dataSource.load(geojsonData, {
                stroke: Cesium.Color.WHITE,
                fill: colorMap[0],
                strokeWidth: 2,
                clampToGround: true
            }).then(ds => {
                const entities = ds.entities.values;
                let colorIndex = 0;
                
                entities.forEach(entity => {
                    if (entity.polygon) {
                        // 四色循环赋值
                        entity.polygon.material = colorMap[colorIndex % 4];
                        entity.polygon.outline = true;
                        entity.polygon.outlineColor = Cesium.Color.WHITE;
                        entity.polygon.outlineWidth = 2;
                        
                        // 拉伸高度(立体效果)
                        entity.polygon.extrudedHeight = 50;
                        entity.polygon.height = 0;
                        
                        colorIndex++;
                    }
                });
                
                cesiumViewer.value.dataSources.add(ds);
                colorMapRef.value = ds;
                
                // 自动飞掠到视图
                cesiumViewRef.value.flyToLocation({
                    longitude: 117.12,
                    latitude: 36.67,
                    height: 400000,
                    duration: 3,
                    heading: 0,
                    pitch: -90,
                });
                
                console.log('✅ 四色图创建成功');
            });
        });
};

总结

热力图+四色图是Cesium三维GIS可视化中最常用、最实用的两大功能。

这里提供的代码均为原生实现、生产环境可用,无需引入任何第三方库,直接复制即可运行。

热力图效果需要大量的数据才能看出效果,如果是人造数据我建议通过AI生成查看效果。

四色图这里也可以增加颜色显示,看起来更丰富。

别再瞎写了!Cesium 模型 360° 环绕,4 套源码全公开,项目直接用

之前在地图上展示的园区模型增加了选中效果,但是对于展示性质的大屏而言,内容一直是静态展示的效果肯定不好。

image.png

所以模型自动环绕展示是绝对的核心亮点功能!无论是展厅大屏演示、项目汇报、还是产品展示,流畅的360°环绕浏览都能让你的三维场景瞬间提升质感。

简单整理了4种开箱即用的环绕方案,从极简入门到专业级平滑动画全覆盖,适配不同项目需求,复制代码直接运行!

flyToLocation + 定时器(极简)

利用之前封装 cesium-viewer 组件做的 flyToLocation 方法实现此功能。

之前封装的 flyToLocation 方法其实就是 cesium.camera.flyTo 方法。

这个方案代码最简单,无需复杂数学计算。支持分段式环绕,适合快速实现需求

可控制停留时间、飞行速度、环绕点数。

image.png

完整代码

// 环绕展示工厂模型
const displayFactoryModel = () => {
    if (!cesiumViewRef.value) return;
    
    const centerLon = 117.104273; // 模型中心点经度
    const centerLat = 36.437867; // 模型中心点纬度
    const radius = 150; // 环绕半径(米)
    const height = 80; // 相机高度
    const duration = 2; // 每个角度飞行时间(秒)
    
    let currentAngle = 0;
    const totalAngles = 8; // 环绕8个点
    const angleStep = 360 / totalAngles;
    
    const flyToNextPoint = () => {
        // 计算当前角度的位置
        const rad = currentAngle * Math.PI / 180;
        const offsetX = radius * Math.cos(rad);
        const offsetY = radius * Math.sin(rad);
        
        // 计算新的经纬度(简化计算,适用于小范围)
        const newLon = centerLon + (offsetX / 111320 / Math.cos(centerLat * Math.PI / 180));
        const newLat = centerLat + (offsetY / 111320);
        
        // 计算相机朝向(朝向中心点)
        const heading = (currentAngle + 180) % 360;
        
        cesiumViewRef.value.flyToLocation({
            longitude: newLon,
            latitude: newLat,
            height: height,
            duration: duration,
            heading: heading,
            pitch: -30, // 稍微俯视的角度
            onComplete: () => {
                currentAngle = (currentAngle + angleStep) % 360;
                setTimeout(flyToNextPoint, 500); // 短暂停留后继续
            }
        });
    };
    
    flyToNextPoint();
};

lookAt + 帧动画(推荐)

这个方案相较于上面的方案比较好的一点就是真正的360°无缝平滑环绕

这种方案无卡顿、无跳跃,动画效果最自然,并且支持无限循环环绕。生产环境推荐首选方案

完整代码

// 环绕展示工厂模型
const displayFactoryModel = () => {
    if (!cesiumViewer.value) return;
    
    const center = Cesium.Cartesian3.fromDegrees(117.104273, 36.437867, 0);
    const radius = 150; // 环绕半径
    const height = 80; // 相机高度
    const duration = 20; // 完整环绕一周的时间(秒)
    
    let startTime = null;
    let animationId = null;
    
    const animateOrbit = (timestamp) => {
        if (!startTime) startTime = timestamp;
        const elapsed = (timestamp - startTime) / 1000;
        
        // 计算当前角度(0到2π)
        const angle = (elapsed / duration) * 2 * Math.PI;
        
        // 计算相机位置(圆形轨道)
        const cameraX = center.x + radius * Math.cos(angle);
        const cameraY = center.y + radius * Math.sin(angle);
        const cameraZ = center.z + height;
        const cameraPosition = new Cesium.Cartesian3(cameraX, cameraY, cameraZ);
        
        // 设置相机位置和朝向(看向中心点)
        cesiumViewer.value.camera.lookAt(
            cameraPosition,
            center, // 看向中心点
            new Cesium.Cartesian3(0, 0, 1)  // up方向
        );
        
        // 继续动画
        animationId = requestAnimationFrame(animateOrbit);
    };
    
    // 开始动画
    animationId = requestAnimationFrame(animateOrbit);
    
    // 返回停止函数(可选)
    return () => {
        if (animationId) {
            cancelAnimationFrame(animationId);
        }
    };
};

flyTo + 曲线路径

基于样条曲线生成平滑路径。支持自定义轨迹点、飞行总时长。

这个方案可以实现复杂环绕、俯冲、拉升等动作,但是如果不是动态模型运动没太大必要用这个。

完整代码

// 环绕展示工厂模型
const displayFactoryModel = () => {
    if (!cesiumViewer.value) return;
    
    const center = Cesium.Cartesian3.fromDegrees(117.104273, 36.437867, 0);
    const radius = 150;
    const height = 80;
    const points = 12; // 路径点数
    const duration = 30; // 总飞行时间
    
    // 创建路径点
    const positions = [];
    for (let i = 0; i <= points; i++) {
        const angle = (i / points) * 2 * Math.PI;
        const x = center.x + radius * Math.cos(angle);
        const y = center.y + radius * Math.sin(angle);
        const z = center.z + height;
        positions.push(new Cesium.Cartesian3(x, y, z));
    }
    
    // 相机沿路径飞行
    cesiumViewer.value.camera.flyTo({
        destination: positions,
        orientation: {
            heading: Cesium.Math.toRadians(0),
            pitch: Cesium.Math.toRadians(-30),
            roll: 0.0
        },
        duration: duration,
        complete: () => {
            console.log('✅ 环绕展示完成');
        }
    });
};

camera.rotate 旋转(极简)

这种方案代码量最少,一行核心逻辑。直接使用原地旋转视角,不改变相机位置。

但是展示效果一般,只能原地自转,不能环绕。

完整代码

// 环绕展示工厂模型
const displayFactoryModel = () => {
    if (!cesiumViewer.value) return;
    
    // 先飞到模型上方
    cesiumViewRef.value.flyToLocation({
        longitude: 117.104273,
        latitude: 36.437867,
        height: 80,
        duration: 3,
        heading: 0,
        pitch: -30,
        onComplete: () => {
            // 开始旋转
            let angle = 0;
            const rotateInterval = setInterval(() => {
                angle = (angle + 1) % 360;
                cesiumViewer.value.camera.setView({
                    orientation: {
                        heading: Cesium.Math.toRadians(angle),
                        pitch: Cesium.Math.toRadians(-30),
                        roll: 0.0
                    }
                });
            }, 50); // 每50ms旋转1度
            
            // 10秒后停止
            setTimeout(() => {
                clearInterval(rotateInterval);
                console.log('✅ 旋转结束');
            }, 10000);
        }
    });
};

总结

模型环绕展示是Cesium展示模型非常好的一种方案,尤其是做会议室大屏使用。

展示修效果还是相当不错的,如果没有特殊要求,可以考虑使用 lookAt+帧动画,这是综合体验最优的方案。

强烈建议大家使用此方案,流畅不卡顿,用户体验直接拉满!

❌