Cesium 加载geojson数据类型点线面

1.获取geojson数据,本地新建一个.ts文件放置数据导出,并引入

 获取geojson数据:

DataV.GeoAtlas地理小工具系列

import { scGeojson } from './geojson';

2.加载面

const addPolygonEvt = () => {
	viewer.dataSources.add(
		Cesium.GeoJsonDataSource.load(scGeojson, {
			clampToGround: true, // 贴地
			fill: Cesium.Color.AZURE.withAlpha(0.5),
		}),
	);
};

因为面数据贴地,边界线消失,所以,将面数据转为多线数据,加载一次边界线

3.加载边界线

import { polygonToLine, polygon } from '@turf/turf';
const addPolygonLine = () => {
	// 设置一个空数组,用来放置每个面的边界,geojson数据
	const lineArr: any[] = [];
	scGeojson.features.map((it) => {
		if (it.geometry && it.geometry.coordinates) {
			it.geometry.coordinates.map((item) => {
				let line = polygonToLine(polygon(item)); // 把多面转为多线
				lineArr.push(line);
			});
		}
	});
	// 1.遍历线数组,可以使用加载实体线方式,把每个面的边界线加载出来
	// 2.或则使用加载geojson数据方法,加载出来
	lineArr.map((it) => {
        // 加载实体方式
	    // viewer.entities.add({
		// 	polyline: {
		// 		positions: Cesium.Cartesian3.fromDegreesArray(
		// 			flatten(it.geometry.coordinates),
		// 		),
		// 		material: Cesium.Color.AQUA,
		// 		clampToGround: true,
		// 	},
		// });
        // 加载geojson方式
		viewer.dataSources.add(
			Cesium.GeoJsonDataSource.load(it, {
				clampToGround: true, // 贴地
				stroke: Cesium.Color.AQUA,
				strokeWidth: 1,
			}),
		);
	});
};

4.加载点

import { point, FeatureCollection } from '@turf/turf';
const addGeojsonPoint = () => {
	const pointGeoJson: FeatureCollection = {
		type: 'FeatureCollection',
		features: [],
	};
	scGeojson.features.map((it) => {
		pointGeoJson.features.push(point(it.properties.center, it.properties));
	});
	let data = viewer.dataSources.add(
		Cesium.GeoJsonDataSource.load(pointGeoJson, {}),
	);
	data.then((dataSource: any) => {
		const entities = dataSource.entities.values;
		for (const item in entities) {
			const entity = entities[item];
			// if (entity.point) {
			entity.billboard = {
				image: '/public/images/gg.png',
				color: Cesium.Color.AQUA,
				width: 40,
				height: 40,
				heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 贴地
			};
			entity.label = {
				text: entity.name,
				font: '14px',
				pixelOffset: new Cesium.Cartesian3(0, 30, 0),
				fillColor: Cesium.Color.DARKGREEN,
			};
		}
	});
};

 效果:


hooks.ts代码:

import * as Cesium from 'cesium';
import { popInfo } from './config';
import { scGeojson } from './geojson';
import { polygonToLine, polygon, point, FeatureCollection } from '@turf/turf';
let viewer: any = {};
export function mountedEvt() {
	Cesium.Ion.defaultAccessToken =
		'';
	viewer = new Cesium.Viewer('cesiumContainer', {
		// baseLayerPicker: false,
	});
	mapFlyEvt(104.065735, 30.659462, 2000000);
	addPolygonEvt();
	addPolygonLine();
	addGeojsonPoint();
}
/**
 * @Description 加载geojson点位
 * @Author: wms
 * @Date: 2023-11-21 15:20:34
 */
const addGeojsonPoint = () => {
	const pointGeoJson: FeatureCollection = {
		type: 'FeatureCollection',
		features: [],
	};
	scGeojson.features.map((it) => {
		pointGeoJson.features.push(point(it.properties.center, it.properties));
	});
	let data = viewer.dataSources.add(
		Cesium.GeoJsonDataSource.load(pointGeoJson, {}),
	);
	data.then((dataSource: any) => {
		const entities = dataSource.entities.values;
		for (const item in entities) {
			const entity = entities[item];
			// if (entity.point) {
			entity.billboard = {
				image: '/public/images/gg.png',
				color: Cesium.Color.AQUA,
				width: 40,
				height: 40,
				heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 贴地
			};
			entity.label = {
				text: entity.name,
				font: '14px',
				pixelOffset: new Cesium.Cartesian3(0, 30, 0),
				fillColor: Cesium.Color.DARKGREEN,
			};
		}
	});
	addPopEvt();
};
/**
 * @Description 弹窗
 * @Author: wms
 * @Date: 2023-11-17 11:02:33
 */
export const addPopEvt = () => {
	const dom = document.getElementById('popBox');
	let popBox: any = new Cesium.InfoBox(dom as string | Element);
	viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(
		movement: any,
	) {
		let pickedObject = viewer.scene.pick(movement.position);

		if (
			Cesium.defined(pickedObject) &&
			pickedObject.id instanceof Cesium.Entity
		) {
			var entity = pickedObject.id;
			if (entity.position) {
				// 显示弹窗
				popBox.container.style.visibility = 'visible';
				// 获取位置信息
				let entityPosition = entity.position.getValue(
					viewer.clock.currentTime,
				);
				// 传递数据,由于我定义了一个map.js文件,所以没办法把点位数据直接传递给页面,只能用eventBus传递两个文件的数据
				popInfo.value = entity.properties;
				// 监听 Viewer 的 postRender 事件,在地图移动时更新弹窗位置
				viewer.scene.postRender.addEventListener(function () {
					try {
						if (entityPosition !== null) {
							let screenPosition =
								Cesium.SceneTransforms.wgs84ToWindowCoordinates(
									viewer.scene,
									entityPosition,
								);
							if (screenPosition) {
								let leftOffset =
									screenPosition.x -
									popBox.container.clientWidth / 2;
								let topOffset =
									screenPosition.y -
									popBox.container.clientHeight -
									18;
								popBox.container.style.left = leftOffset + 'px';
								popBox.container.style.top = topOffset + 'px';
							}
						}
					} catch (error) {
						console.log(error);
					}
				});
			} else {
				popBox.container.style.visibility = 'hidden';
			}
		} else {
			// 隐藏弹窗
			popBox.container.style.visibility = 'hidden';
		}
	}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};
/**
 * @Description 加载面数据
 * @Author: wms
 * @Date: 2023-11-21 09:36:22
 */
export const addPolygonEvt = () => {
	viewer.dataSources.add(
		Cesium.GeoJsonDataSource.load(scGeojson, {
			clampToGround: true, // 贴地
			fill: Cesium.Color.AZURE.withAlpha(0.5),
		}),
	);
};
/**
 * @Description 加载面边界
 * @Author: wms
 * @Date: 2023-11-21 14:59:04
 */
const addPolygonLine = () => {
	// 设置一个空数组,用来放置每个面的边界,geojson数据
	const lineArr: any[] = [];
	scGeojson.features.map((it) => {
		if (it.geometry && it.geometry.coordinates) {
			it.geometry.coordinates.map((item) => {
				let line = polygonToLine(polygon(item)); // 把多面转为多线
				lineArr.push(line);
			});
		}
	});
	// 遍历线数组,使用加载实体线方式,把每个面的边界线加载出来
	// 或则使用加载geojson数据方法,加载出来
	lineArr.map((it) => {
		// viewer.entities.add({
		// 	polyline: {
		// 		positions: Cesium.Cartesian3.fromDegreesArray(
		// 			flatten(it.geometry.coordinates),
		// 		),
		// 		material: Cesium.Color.AQUA,
		// 		clampToGround: true,
		// 	},
		// });
		viewer.dataSources.add(
			Cesium.GeoJsonDataSource.load(it, {
				clampToGround: true, // 贴地
				stroke: Cesium.Color.AQUA,
				strokeWidth: 1,
			}),
		);
	});
};
/**
 * @Description 数组扁平化处理
 * @Author: wms
 * @Date: 2023-11-21 14:50:59
 */
const flatten = (arr: any[]) => {
	let result: number[] = [];
	for (let i = 0; i < arr.length; i++) {
		if (Array.isArray(arr[i])) {
			result = result.concat(flatten(arr[i]));
		} else {
			result.push(arr[i]);
		}
	}
	return result;
};
/**
 * @Description 地图飞行动画
 * @Author: wms
 * @Date: 2023-11-21 15:11:14
 */
const mapFlyEvt = (lon: number, lat: number, height: number) => {
	const position = Cesium.Cartesian3.fromDegrees(lon, lat, height);
	// flyTo快速切换视角,带飞行动画,可以设置飞行时长
	viewer.camera.flyTo({
		destination: position,

		orientation: {
			heading: Cesium.Math.toRadians(0),

			pitch: Cesium.Math.toRadians(-90),

			roll: Cesium.Math.toRadians(0),
		},

		duration: 3, // 单位秒
	});
};
### Cesium 加载 GeoJSON 数据失败的原因及解决方案 #### 可能原因分析 1. **跨域问题** 如果 GeoJSON 文件托管在不同的服务器上,而该服务器未设置允许跨域访问,则可能导致加载失败。浏览器的安全策略会阻止这种请求[^4]。 2. **文件路径错误** 地址配置可能存在问题,例如 URL 路径拼写错误或者资源不可达。如果指定的 GeoJSON 文件不存在或无法被正确解析,也会导致加载失败[^2]。 3. **数据格式不符合标准** GeoJSON 的结构必须严格遵循其定义的标准。任何字段缺失、多余属性或其他语法错误都会使 Cesium 解析失败。 4. **网络延迟或超时** 当网络状况不佳时,可能会因为请求时间过长而导致加载中断。这种情况通常表现为控制台报错 `timeout` 或者类似的提示信息。 5. **Cesium 版本兼容性** 不同版本的 Cesium 对于某些功能的支持程度不同。旧版可能存在 bug 导致特定类型的 GeoJSON 数据无法正常渲染[^1]。 --- #### 解决方案 ##### 方法一:处理跨域问题 通过配置代理来规避跨域限制是一种常见做法。可以在项目根目录下的 `vue.config.js` 中添加如下代码实现反向代理: ```javascript module.exports = { devServer: { proxy: { '/geojson': { // 需要代理的目标前缀 target: 'http://your-server.com', // 实际服务地址 changeOrigin: true, pathRewrite: { '^/geojson': '' } // 移除前缀匹配部分 } } } }; ``` 这样可以将 `/geojson/*` 开头的所有请求重定向到目标主机并伪装成来自同一源的流量。 ##### 方法二:验证 GeoJSON 合法性 利用在线工具(如 http://geojsonlint.com/)检查输入的数据是否完全符合规范。确保几何对象类型正确无误,并且坐标数组按照逆时针方向排列闭合多边形边界线串。 ##### 方法三:调试日志定位具体异常位置 开启详细的开发者模式以便观察具体的 HTTP 请求状态码以及响应体内容。借助 Chrome 浏览器内置 Network 工具跟踪整个过程中的每一个环节是否有异常发生[^3]。 ##### 方法四:升级至最新稳定发行版 考虑到软件迭代过程中修复了许多已知缺陷,建议始终使用官方推荐的新近发布版本以获得更好的体验效果。 --- ### 示例代码片段 下面展示了一个简单的例子说明如何正确引入外部 GeoJSON 并附加样式规则: ```javascript viewer.dataSources.add(Cesium.GeoJsonDataSource.load('path/to/file.geojson', { stroke: Cesium.Color.HOTPINK, fill: Cesium.Color.POWDERBLUE.withAlpha(0.5), strokeWidth: 3 })); ``` 上述脚本假设当前工作环境已经初始化好 viewer 实例变量并且能够顺利获取远程资源链接指向有效的 GeoJSON 文档。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小满blue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值