<script>
// 初始化Cesium Viewer
// 定义两个多边形实体
var polygon1 = viewer.entities.add({
name: 'Polygon 1',
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray([
-108.3, 41.0,
-108.4, 41.0,
-108.5, 40.5
]),
material: Cesium.Color.RED.withAlpha(0.2),
}
});
var polygon2 = viewer.entities.add({
name: 'Polygon 2',
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray([
-108.34, 41.0,
-108.44, 41.0,
-108.54, 40.5
]),
material: Cesium.Color.BLUE.withAlpha(0.2),
}
});
// 从Cesium实体中获取多边形坐标
function getPolygonCoordinates(polygonEntity) {
var positions = polygonEntity.polygon.hierarchy.getValue();
var coordinates = [];
console.log(polygonEntity.polygon.hierarchy.getValue());
positions.forEach(function (position) {
var cartographic = Cesium.Cartographic.fromCartesian(position);
var longitude = Cesium.Math.toDegrees(cartographic.longitude);
var latitude = Cesium.Math.toDegrees(cartographic.latitude);
coordinates.push([longitude, latitude]);
});
// 确保闭合多边形
if (coordinates.length > 0) {
coordinates.push(coordinates[0]);
}
return coordinates;
}
// 获取两个多边形的坐标
var coords1 = getPolygonCoordinates(polygon1);
var coords2 = getPolygonCoordinates(polygon2);
// 使用Turf.js计算两个多边形的交集
var poly1 = turf.polygon([coords1]);
var poly2 = turf.polygon([coords2]);
var intersection = turf.intersect(poly1, poly2);
// 将交集区域加载到Cesium中
if (intersection) {
var intersectionCoords = intersection.geometry.coordinates[0];
var intersectionDegreesArray = [];
intersectionCoords.forEach(function (coord) {
intersectionDegreesArray.push(coord[0], coord[1]);
});
viewer.entities.add({
name: 'Intersection Polygon',
polygon: {
hierarchy: Cesium.Cartesian3.fromDegreesArray(intersectionDegreesArray),
material: Cesium.Color.GREEN.withAlpha(1),
}
});
} else {
console.log('No intersection found');
}
viewer.zoomTo(viewer.entities);
// 移除一个多边形
</script>