cesium 使用 GeoJsonDataSource 加载 geoJson 数据,渲染 Polygon、polyline、Text 贴地配置

发布时间 2023-04-18 17:03:08作者: 贝尔塔猫

原文地址:https://juejin.cn/post/7029592051154944007

 

export function renderPolygon(geojson: any, zoomto: Boolean = true) {
    const viewer = window.viewer
    const dataSource = new Cesium.GeoJsonDataSource()

    // [cesium加载geoJson数据] https://juejin.cn/post/7029592051154944007
    dataSource.load(geojson, { clampToGround: true }).then(() => {
        viewer.dataSources.add(dataSource)
        const entities = dataSource.entities.values
        for (let i = 0; i < entities.length; i++) {
            const entity = entities[i]
            // 修改 entity 样式
            entity.polygon.material = Cesium.Color.fromCssColorString('#ff0000').withAlpha(0.5)
            // 添加 entity 的 polyline
            entity.polyline = { positions: entity.polygon.hierarchy._value.positions, width: 2, material: Cesium.Color.fromCssColorString('#ffff00') }
            // 获取一个 entity 的中心位置
            const center = Cesium.BoundingSphere.fromPoints(entity.polygon.hierarchy._value.positions).center
            // 设置中心位置
            entity.position = center
            // 添加 text
            entity.label = {
                text: entity.properties.name,
                color: Cesium.Color.fromCssColorString('#fff'),
                font: 'normal 32px MicroSoft YaHei',
                showBackground: true,
                scale: 0.5,
                horizontalOrigin: Cesium.HorizontalOrigin.LEFT_CLICK,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                disableDepthTestDistance: 10000.0
            }
        }

        if (zoomto) {
            viewer.zoomTo(dataSource)
        }
    })

    return dataSource
}