普通视图

发现新文章,点击刷新页面。
昨天 — 2026年3月24日首页

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

作者 李剑一
2026年3月24日 09:26

之前 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 套源码全公开,项目直接用

作者 李剑一
2026年3月23日 21:12

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

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+帧动画,这是综合体验最优的方案。

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

昨天以前首页

Cesium 海量点位不卡顿!图标动态聚合效果深度解析,看完直接抄代码!

作者 李剑一
2026年3月19日 09:45

接上文# 告别冗余代码!Cesium点位图标模糊、重叠?自适应参数调优攻略,一次封装终身复用!,在地图上创建图标是基础操作,但是当地图上的图标过多的时候展示效果其实并不好。

毕竟谁也不想看到密密麻麻的图标,所以部分距离相近的图标应该聚合在一起,形成一个聚合图标展示出来。

image.png

在Cesium开发中,图标聚合能够解决海量图标重叠、界面杂乱、性能卡顿等问题。

尤其在智慧安防、智慧园区、设备监控等场景,几十个甚至上百个摄像头/设备图标挤在一块,不仅看不清,还会严重影响地图流畅度。

解决方案

通过监听相机高度,高度超过阈值,自动开启聚合。

根据计算屏幕像素距离,把三维坐标转成屏幕坐标,算两点多远,距离小于设定值,归为一组。

image.png

这时候隐藏原始图标,只显示聚合图标。

生成聚合点:显示图标+数量,拉近后自动散开。

实现代码

计算屏幕距离 + 判断是否在屏幕内。是聚合的核心基础:把三维坐标转屏幕坐标,再算距离。

/**
 * 计算两点在屏幕上的像素距离
 */
const calculateScreenDistance = (pos1, pos2) => {
    if (!viewer.value || !viewer.value.scene) return Infinity
    
    const scene = viewer.value.scene
    try {
        // 世界坐标 → 屏幕坐标
        const screenPos1 = Cesium.SceneTransforms.worldToWindowCoordinates(scene, pos1)
        const screenPos2 = Cesium.SceneTransforms.worldToWindowCoordinates(scene, pos2)
        
        if (!screenPos1 || !screenPos2) return Infinity
        
        // 勾股定理算像素距离
        const dx = screenPos1.x - screenPos2.x
        const dy = screenPos1.y - screenPos2.y
        return Math.sqrt(dx * dx + dy * dy)
    } catch (error) {
        return Infinity
    }
}

/**
 * 检查点是否在屏幕上可见
 */
const isPositionOnScreen = (position) => {
    if (!viewer.value || !viewer.value.scene) return false
    try {
        const screenPos = Cesium.SceneTransforms.worldToWindowCoordinates(viewer.value.scene, position)
        return screenPos != null
    } catch (error) {
        return false
    }
}

生成聚合点,图标更大、创建label显示当前标签数量更明显。

/**
 * 创建聚合图标
 */
const createClusterIcon = (clusterData) => {
    if (!viewer.value) return null
    const { icons, type, center } = clusterData
    const count = icons.length

    // 坐标转换
    const cartographic = Cesium.Cartographic.fromCartesian(center)
    const longitude = Cesium.Math.toDegrees(cartographic.longitude)
    const latitude = Cesium.Math.toDegrees(cartographic.latitude)

    // 创建聚合实体
    const clusterId = `cluster_${type}_${Date.now()}`
    const entity = viewer.value.entities.add({
        id: clusterId,
        position: center,
        billboard: {
            image: getClusterIconUrl(type),
            scale: 1.2,
            width: 40,
            height: 40,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            disableDepthTestDistance: Number.POSITIVE_INFINITY
        }
    })

    // 聚合数量标签
    const typeName = getTypeDisplayName(type)
    entity.label = {
        text: `${typeName} ${count}个`,
        font: '14px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        pixelOffset: new Cesium.Cartesian2(0, -50),
        showBackground: true,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
    }

    // 存入聚合列表
    clusterEntities.set(clusterId, { entity, icons, type, center })
    return entity
}

动态计算聚合阈值,通过遍历图标 → 分组 → 合并/显示,自动隐藏原始图标,显示聚合点。

/**
 * 更新图标聚合状态
 */
const updateClustering = () => {
    if (!viewer.value || iconEntities.size === 0) return
    clearClusters()

    // 关闭聚合 = 显示全部
    if (!isClusteringEnabled.value) {
        showAllIcons()
        return
    }

    // 动态阈值:相机越高,聚合越明显
    const cameraHeight = viewer.value.camera.positionCartographic.height
    const dynamicClusterDistance = Math.min(
        MAX_SCREEN_CLUSTER_DISTANCE,
        SCREEN_CLUSTER_DISTANCE + (cameraHeight - CLUSTER_THRESHOLD) / 50
    )

    // 收集所有图标
    const allIcons = []
    iconEntities.forEach((iconData, id) => {
        const position = iconData.entity.position.getValue(Cesium.JulianDate.now())
        allIcons.push({ id, entity: iconData.entity, position, type: iconData.type })
    })

    // 先隐藏所有图标
    allIcons.forEach(icon => icon.entity.show = false)

    // 聚类算法
    const clusters = []
    const visited = new Set()

    for (let i = 0; i < allIcons.length; i++) {
        if (visited.has(i)) continue
        const current = allIcons[i]
        if (!isPositionOnScreen(current.position)) continue

        const cluster = [current]
        visited.add(i)

        // 寻找附近图标
        for (let j = i + 1; j < allIcons.length; j++) {
            if (visited.has(j)) continue
            const other = allIcons[j]
            if (!isPositionOnScreen(other.position)) continue

            const dist = calculateScreenDistance(current.position, other.position)
            if (dist <= dynamicClusterDistance) {
                cluster.push(other)
                visited.add(j)
            }
        }
        clusters.push(cluster)
    }

    // 生成聚合点 / 显示单个图标
    clusters.forEach(cluster => {
        if (cluster.length === 1) {
            cluster[0].entity.show = true
        } else {
            // 计算中心点
            let centerX = 0, centerY = 0, centerZ = 0
            cluster.forEach(icon => {
                centerX += icon.position.x
                centerY += icon.position.y
                centerZ += icon.position.z
            })
            const center = new Cesium.Cartesian3(
                centerX / cluster.length,
                centerY / cluster.length,
                centerZ / cluster.length
            )

            createClusterIcon({
                icons: cluster.map(c => c.id),
                type: 'camera',
                center
            })
        }
    })
}

总结

Cesium 图标聚合原理上很简单:

算距离 → 分组 → 隐藏/显示 → 生成聚合点

在园区级别的模型上其实启不启用影响不大,但是在城市级别,或者是多地区复杂情况的模型上还是有必要的。

能够极大的提升加载的流畅度,减少操作的卡顿。

❌
❌