自学内容网 自学内容网

【WebGIS】Cesium:GeoJSON加载

GeoJSON 是一种常用的地理空间数据格式,它用于表示简单的地理要素及其属性,并且被广泛应用于 Web 地图和 GIS 系统中。在 Cesium 中,GeoJSON 文件可以很方便地加载到三维场景中展示,并且可以添加样式和事件处理。本文将为你提供详细的渐进式学习教程,帮助你逐步掌握如何在 Cesium 中加载和使用 GeoJSON 数据。

初识 GeoJSON

GeoJSON 是一种基于 JSON(JavaScript Object Notation)的格式,用于表示地理要素,它支持点、线、面(Polygon)、多点、多线和多面等几何对象。GeoJSON 的数据结构包括以下基本部分:

  • Feature:一个地理要素。
  • FeatureCollection:多个 Feature 的集合。
  • 几何类型:Point(点)、LineString(线)、Polygon(面)等。

GeoJSON 示例

一个简单的 GeoJSON 文件可能像这样:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [102.0, 0.5]
      },
      "properties": {
        "name": "Sample Point"
      }
    }
  ]
}

Cesium 中加载 GeoJSON

在 Cesium 中,加载 GeoJSON 非常简单。Cesium 提供了 GeoJsonDataSource 类,用于解析和加载 GeoJSON 数据。通过该类,你可以轻松地将 GeoJSON 文件加载到场景中。

基础用法

以下是加载一个简单 GeoJSON 文件的代码示例:

const viewer = new Cesium.Viewer('cesiumContainer');

// 加载 GeoJSON 文件
Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson')
    .then(function(dataSource) {
        viewer.dataSources.add(dataSource);
        viewer.flyTo(dataSource);  // 自动飞到数据范围
    })
    .catch(function(error) {
        console.error(error);
    });

这段代码演示了如何使用 GeoJsonDataSource.load() 方法加载一个 GeoJSON 文件并将其添加到 Cesium 场景中。如果加载成功,Cesium 将会自动将视角飞到加载的 GeoJSON 数据的范围。

本地加载与远程加载

除了加载本地的 GeoJSON 文件外,GeoJsonDataSource 也支持从远程服务器加载 GeoJSON 文件。例如:

Cesium.GeoJsonDataSource.load('https://example.com/your/geojson.geojson')
    .then(function(dataSource) {
        viewer.dataSources.add(dataSource);
    });

GeoJSON 的样式自定义

加载 GeoJSON 后,Cesium 允许你自定义要素的样式,比如点的颜色、线条的宽度和多边形的填充颜色等。样式通过 GeoJsonDataSource.clampToGroundGeoJsonDataSource.stroke 等属性来设置。

Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson', {
    stroke: Cesium.Color.RED,       // 线条颜色
    fill: Cesium.Color.YELLOW.withAlpha(0.6),  // 多边形填充颜色
    strokeWidth: 3,                 // 线条宽度
    markerSymbol: '?',              // 标记符号
    markerSize: 12,                 // 标记大小
    markerColor: Cesium.Color.BLUE  // 标记颜色
}).then(function(dataSource) {
    viewer.dataSources.add(dataSource);
});

在这个例子中,GeoJSON 中的点、线和多边形的样式都被自定义了。你可以根据需求进一步调整这些样式以满足项目的需求。

GeoJSON 数据的动态更新

Cesium 还允许你动态更新或添加 GeoJSON 数据。你可以通过更新 GeoJsonDataSource 来实现这一点。例如,你可以实时地从服务器获取最新的 GeoJSON 数据并更新显示。

const dataSource = new Cesium.GeoJsonDataSource();
viewer.dataSources.add(dataSource);

// 定期更新 GeoJSON 数据
setInterval(function() {
    dataSource.load('https://example.com/updated/geojson-file.geojson');
}, 10000);  // 每 10 秒刷新一次数据

在这个例子中,我们通过定时器每 10 秒从服务器加载新的 GeoJSON 数据,更新 Cesium 场景中的显示。

GeoJSON 的事件处理

Cesium 支持对 GeoJSON 中加载的每个要素(如点、线、面)添加鼠标点击、悬停等交互事件处理器。这可以极大地增强用户与地图的互动体验。

添加点击事件

以下示例展示了如何为 GeoJSON 数据中的要素添加鼠标点击事件:

Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson')
    .then(function(dataSource) {
        viewer.dataSources.add(dataSource);
        const entities = dataSource.entities.values;

        for (let i = 0; i < entities.length; i++) {
            const entity = entities[i];
            
            entity.description = `Name: ${entity.properties.name.getValue()}`;
            
            // 添加点击事件
            viewer.screenSpaceEventHandler.setInputAction(function(click) {
                const pickedObject = viewer.scene.pick(click.position);
                if (Cesium.defined(pickedObject) && pickedObject.id === entity) {
                    alert('Clicked on ' + entity.name);
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }
    });

该代码为每个 GeoJSON 要素添加了点击事件。当用户点击某个要素时,弹出一个对话框显示该要素的名称。

贴附到地形

在 Cesium 场景中,GeoJSON 的几何体默认是悬浮在空中的。如果需要将这些几何体贴附到地形上(例如显示在真实的地形表面上),可以使用 clampToGround 选项。

Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson', {
    clampToGround: true // 将几何体贴附到地形上
}).then(function(dataSource) {
    viewer.dataSources.add(dataSource);
});

这段代码将加载的 GeoJSON 数据贴地显示,使得其更加符合地形的实际形状,尤其是当你使用了真实的 Cesium 世界地形时,这样的显示效果更加自然。

GeoJSON 数据的性能优化

在处理大型 GeoJSON 文件时,可能会遇到性能问题。为了提高性能,Cesium 提供了多种方法进行优化,例如:

  • 使用 simplify 参数来减少几何体的复杂度。
  • 使用服务器端对 GeoJSON 进行预处理,减少数据量。
Cesium.GeoJsonDataSource.load('path/to/large-geojson-file.geojson', {
    clampToGround: true,
    simplify: true // 简化几何体
}).then(function(dataSource) {
    viewer.dataSources.add(dataSource);
});

通过属性加载样式

在 Cesium 中,可以通过 GeoJSON 数据中的属性字段来自定义几何体的高度、颜色等属性。这些属性通常存储在 GeoJSON 的 properties 中,而 Cesium 提供了灵活的 API,可以根据这些属性字段动态设置几何体的外观和行为。

以下是详细的步骤,逐步讲解如何使用 GeoJSON 属性字段来自定义几何体的高度和颜色等属性。

准备 GeoJSON 文件

首先,确保你的 GeoJSON 文件包含有你想用来设置几何体属性的字段。例如,下面是一个包含高度(height)和颜色(color)的 GeoJSON 示例:

{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            102.0,
                            0.0
                        ],
                        [
                            103.0,
                            0.0
                        ],
                        [
                            103.0,
                            1.0
                        ],
                        [
                            102.0,
                            1.0
                        ],
                        [
                            102.0,
                            0.0
                        ]
                    ]
                ]
            },
            "properties": {
                "height": 3000,
                "color": "#ff0000"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [
                    101.5,
                    0.5
                ]
            },
            "properties": {
                "height": 10000,
                "color": "#00ff00"
            }
        }
    ]
}

这个 GeoJSON 文件包含两个要素:一个多边形和一个点,它们都有各自的高度和颜色属性。

加载 GeoJSON 数据

使用 Cesium 的 GeoJsonDataSource 来加载这个 GeoJSON 文件,并通过 entities API 来访问并修改每个几何体的外观和高度。下面是加载的基本代码:

const viewer = new Cesium.Viewer('cesiumContainer');

Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson')
    .then(function(dataSource) {
        viewer.dataSources.add(dataSource);

        const entities = dataSource.entities.values;

        // 遍历所有实体,基于 GeoJSON 中的属性字段来设置高度和颜色
        for (let i = 0; i < entities.length; i++) {
            const entity = entities[i];

            // 访问每个实体的 properties
            const height = entity.properties.height.getValue();
            const color = Cesium.Color.fromCssColorString(entity.properties.color.getValue());

            // 设置多边形或点的高度和颜色
            if (entity.polygon) {
                entity.polygon.extrudedHeight = height;  // 设置多边形的高度
                entity.polygon.material = color;         // 设置多边形的颜色
            } else if (entity.point) {
                entity.point.pixelSize = 10;             // 设置点的大小
                entity.point.color = color;              // 设置点的颜色
                entity.position = Cesium.Cartesian3.fromDegrees(
                    entity.position.getValue(Cesium.JulianDate.now()).longitude,
                    entity.position.getValue(Cesium.JulianDate.now()).latitude,
                    height                                  // 设置点的高度
                );
            }
        }
    })
    .catch(function(error) {
        console.error(error);
    });
  • 访问 properties 字段entity.properties 包含了 GeoJSON 中的自定义属性字段。通过 entity.properties.fieldName.getValue() 可以获取相应的值。
  • 设置高度:对于 polygon,可以通过 entity.polygon.extrudedHeight 来设置其拉伸高度。对于 point,可以通过 entity.position 设置其在三维空间中的位置,高度值包含在第三个参数中。
  • 设置颜色:可以通过 Cesium.Color.fromCssColorString() 方法,将 GeoJSON 属性中的颜色字符串转换为 Cesium 中的颜色对象,并应用到 polygon.materialpoint.color 中。

通过属性加载多边形

Cesium Viewer 初始化

const viewer = new Cesium.Viewer('cesiumContainer', {
    timeline: false,
    animation: false,
    infoBox: false,
    imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
        url: "http://t0.tianditu.gov.cn/vec_w/wmts?tk=" + MAP_KEY,
        layer: "vec",
        style: "default",
        tileMatrixSetID: "w",
        format: "tiles",
        maximumLevel: 18
    })
});
  • 创建一个 Cesium.Viewer 实例,并设置基本配置选项,例如关闭时间轴和动画控件,同时使用天地图作为底图。

加载 GeoJSON 文件

Cesium.GeoJsonDataSource.load('path/to/your/geojson-file.geojson', {
    clampToGround: true
}).then(function(dataSource) {
    // 处理加载成功的逻辑
});
  • 使用 Cesium.GeoJsonDataSource.load 方法加载 GeoJSON 文件,并使用 clampToGround: true 选项确保几何贴合地面。

遍历和渲染实体

const entities = dataSource.entities.values;
for (let i = 0; i < entities.length; i++) {
    const entity = entities[i];
    if (entity.polygon) {
        const properties = entity.properties;
        const height = properties.height ? properties.height.getValue() : 0;
        const colorValue = properties.color ? properties.color.getValue() : '#ffffff';
        entity.polygon.extrudedHeight = height;
        entity.polygon.material = Cesium.Color.fromCssColorString(colorValue);
        entity.polygon.outline = false;
    }
}
  • 遍历 dataSource.entities.values,该数组包含所有加载的实体。
  • 通过 properties 对象获取每个多边形的 heightcolor 属性,并分别用于设置 extrudedHeight(拉伸高度)和 material(颜色)。
  • 使用 Cesium.Color.fromCssColorString 将颜色字符串转换为 Cesium 的颜色对象。

调整视角

viewer.zoomTo(dataSource);
  • 使用 viewer.zoomTo 方法自动调整视角,使加载的所有实体都在视野范围内。

结语

通过本文,你已经了解了如何在 Cesium 中加载、展示和交互 GeoJSON 数据。Cesium 提供了强大的 API 来自定义样式、处理事件、动态更新数据,并且可以高效地加载大型数据集。在实际项目中,你可以结合 Cesium 的其他功能,如 3D Tiles、地形和影像图层,构建出复杂的三维可视化应用。


原文地址:https://blog.csdn.net/2303_80346267/article/details/142876419

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!