之前在网上搜到的获取中心点的方法如下:
// 多边形的坐标集合(如果已经获取到了,就跳过这一步)
var polygon_point_arr = polygon_point_entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
// 根据坐标集合构造BoundingSphere获取中心点坐标
let center_point = Cesium.BoundingSphere.fromPoints(polygon_point_arr).center
// 设置点标记的坐标(这一步将中心点转到地球表面)
polygon_point_entity.position = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(center_point);
// 添加点标记
polygon_point_entity.label = {
// 点标记参数
}
但是如果多边形不太规则或者点比较多的情况下,标记的位置就不在中心点了,会有偏移,例如下图
原因:boundingsphere
计算的中心点是外接圆的圆心,所以导致了中心点会在图形外。
相关资料参考的是:https://www.lmlphp.com/user/58093/article/item/771705/
解决方案: 使用 turf.js
来计算。
turf.js 中文网:https://turfjs.fenxianglu.cn/
代码:turf.js 版本是 6.5.0
// 多边形的坐标集合(如果已经获取到了,就跳过这一步)
var polygon_point_arr = polygon_point_entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
// 保存转换后的点数组,这个格式必须按照 turf 的要求来
let turf_arr = [[]];
// 坐标转换
polygon_point_arr.forEach(val => {
let polyObj = {}
// 空间坐标转世界坐标(弧度) 同 Cesium.Cartographic.fromCartesian
let cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(val)
// 弧度转为角度(经纬度)
polyObj.lon = Cesium.Math.toDegrees(cartographic.longitude)
polyObj.lat = Cesium.Math.toDegrees(cartographic.latitude)
turf_arr[0].push([polyObj.lon, polyObj.lat])
})
// turf 需要将整个点闭合,所以最后一个点必须和起点重合。
turf_arr[0].push(turf_arr[0][0])
let turf_position = turf.polygon(turf_arr)
let turf_position_point = turf.centerOfMass(turf_position)
// 设置点标记坐标
polygon_point_entity.position = Cesium.Cartesian3.fromDegrees(turf_position_point.geometry.coordinates[0], turf_position_point.geometry.coordinates[1], 0)
// 添加点标记
polygon_point_entity.label = {
// 点标记参数
}