cesium中geojson数据渲染

如何在cesium的地图上添加geojson数据,并计算中心点,在中心点打上图标和文字

效果图:

一、创建地图

js 复制代码
import * as Cesium from "cesium"; 
Cesium.Ion.defaultAccessToken = key; 
const viewer = new Cesium.Viewer(id);

二、加载geojson数据

使用Cesium.GeoJsonDataSource.load(file,option)加载geojson文件、或者是geojson的数据,遍历每个区域使用viewer.entities.add()用于添加中心点的图标。使用viewer.entities.remove(entity)可以移除实体。

js 复制代码
let lastAddedDataSource = null
let center = []
const dataSourcePromise = Cesium.GeoJsonDataSource.load(geoJsonObject, {
    // 可选参数
    clampToGround: true, // 使数据贴合地形
    stroke: Cesium.Color.HOTPINK,
    // fill: Cesium.Color.GREEN.withAlpha(0.5),
    strokeWidth: 3,
  });

  dataSourcePromise
    .then(function (dataSource) {
      // 添加数据源到Viewer
      viewer.dataSources.add(dataSource);

      lastAddedDataSource = dataSource;

      // 获取所有实体
      const entities = dataSource.entities.values;;

      // 遍历每个实体
      for (let i = 0; i < entities.length; i++) {
        const entity = entities[i];

        // 读取properties信息
        const properties = entity.properties;
        
        //每个区域添加随机颜色
        entity.polygon.material = Cesium.Color.fromRandom({
            alpha: 0.7,
            minimumRed: 0.1,
            minimumGreen: 0.1,
            minimumBlue: 0.1,
          });

        //中心点
        const positions = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
            
        // 计算中心点
        const centerPosition = computePolygonCentroid(positions);

          // 在中心点添加图标
          let point = viewer.entities.add({
            id: id,
            name: name,
            position: centerPosition,
            label: {
                text: properties?.NAME?._value,
                scale: 0.5,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(0, 40),
            },
            billboard: {
              image: icon, // 图标路径
              width: 50,
              height: 50,
              verticalOrigin: Cesium.VerticalOrigin.TOP,
              disableDepthTestDistance: Number.POSITIVE_INFINITY, // 确保图标始终可见
              pixelOffset: new Cesium.Cartesian2(0, -25),
            },
            monitoItems:  {
                省: properties["省"]?._value,
                市: properties["市"]?._value,
                县: properties["县"]?._value,
            },
          });

          center.push(point);
      }

      // 自动缩放到数据范围
      viewer.zoomTo(dataSource);
    })
    .catch(function (error) {
      console.error("Error loading GeoJSON:", error);
    });
    

计算中心点的方法

js 复制代码
function computePolygonCentroid(positions) {
    const cartographics = positions.map(p => Cesium.Cartographic.fromCartesian(p));
    
    // 转换为经纬度坐标
    const points = cartographics.map(c => {
        return {
            lon: Cesium.Math.toDegrees(c.longitude),
            lat: Cesium.Math.toDegrees(c.latitude)
        };
    });
    
    // 确保多边形是闭合的
    if (points.length > 0 && 
        (points[0].lon !== points[points.length-1].lon || 
         points[0].lat !== points[points.length-1].lat)) {
        points.push({...points[0]});
    }
    
    // 计算中心点
    let area = 0;
    let centroidLon = 0;
    let centroidLat = 0;
    
    for (let i = 0; i < points.length - 1; i++) {
        const p1 = points[i];
        const p2 = points[i + 1];
        
        const f = p1.lon * p2.lat - p2.lon * p1.lat;
        centroidLon += (p1.lon + p2.lon) * f;
        centroidLat += (p1.lat + p2.lat) * f;
        area += f;
    }
    
    area /= 2;
    centroidLon /= (6 * area);
    centroidLat /= (6 * area);
    
    // 转换回笛卡尔坐标
    return Cesium.Cartesian3.fromDegrees(centroidLon, centroidLat);
}

移除geojson数据

js 复制代码
// 移除GeoJSON
 viewer.dataSources.remove(lastAddedDataSource)
相关推荐
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅2 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊3 小时前
jwt介绍
前端
爱敲代码的小鱼3 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
Cobyte3 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc