基于此网站:https://carto.com/blog/center-of-points/,我尝试为一组经/纬度点计算加权平均值。该站点以SQL代码显示计算,我专门查看测试数据集,如下所示:
Data Table
country lat lon
------- -------- ---------
Tonga -21.1333 -175.2
Tuvalu -8.53333 179.2167
结果是:
avg_lon avg_lon_naive avg_lat
------- ------------- -------
-177.992 2.00833 -14.9333
现在我尝试将其转换为javascript,如下所示:
// Calculate weighted average of points in lat/lon
// mypoint = [lat, lon ]
var mypoint1 = [-21.1333, -175.2];
var mypoint2 = [-8.53333, 179.2167];
//Weighted LON
var zeta = (Math.sin(Math.PI * mypoint1[1] / 180) + Math.sin(Math.PI *
mypoint2[1] / 180)) / 2;
console.log(zeta);
var xi = (Math.cos(Math.PI * mypoint1[1] / 180) + Math.sin(Math.PI *
mypoint2[1] / 180)) / 2;
console.log(xi);
var avglon = 180 * Math.atan2(zeta, xi) / Math.PI;
console.log("Average longitude: " + avglon);
//Weighted LAT
var avglat = (mypoint1[0] + mypoint2[0]) / 2;
console.log("Average latitude: " + avglat);
产生以下结果:
-0.03500355257793927
-0.49141106053653333
Average longitude: -175.92566317222995
Average latitude: -14.833314999999999
Press any key to continue...
为什么我的JavaScript案例会有不同的结果?我在代码中做错了吗?遗漏了一些东西,进行了转换或类似的操作?
还是SQL和JavaScript中的atan2或PI有什么区别?
任何指针都将受到高度赞赏。
编辑:对于LAT计算,我已经开始相信原始帖子有错误。由于Lat的计算相对容易,因此我们可以看到:
2 x -14.9333 = 29,8666
不是给定的原始经度点的结果
-21.1333 +(-8.53333) = -29.6666299
答案 0 :(得分:1)
实际上,我认为这两种方法都不正确。 在球体上,我将平均3D向量。 在python中看起来像:
import numpy as np
DEGREE = np.pi/180.
RAD = 1./DEGREE
def lon_lat_naive( inList ):
return np.mean( inList,axis=0)
def lon_lat_full_vector( inList ):
vec = [ [ np.cos( lat * DEGREE ) * np.cos( lon * DEGREE ), np.cos(lat* DEGREE ) * np.sin( lon * DEGREE ), np.sin( lat * DEGREE ) ] for lon, lat in inList ]
# ~ print vec
vec = np.sum( vec, axis=0)
vec /= np.linalg.norm( vec )
# ~ print vec
lat = np.arcsin( vec[2] ) * RAD
lon = np.arctan2( vec[1], vec[0] ) * RAD
return [ lon, lat ]
a = np.array( [10, 60 ])
b = np.array( [20, 80 ])
print( lon_lat_naive( np.array( [ a, b ] ) ) )
print( lon_lat_full_vector( np.array( [ a, b ] ) ) )
Tonga = np.array( [ -175.2, -21.1333 ])
Tuvalu = np.array( [ 179.2167, -8.53333 ])
tt = np.array( [Tonga, Tuvalu ] )
print( lon_lat_naive( tt ) )
print( lon_lat_full_vector( tt ) )
提供:
[15. 70.]
[12.573012941928377, 70.05362118882975]
[ 2.00835 -14.833315]
[-178.07333636886855, -14.850146658102775]
这与您和您的网页都不同,但是应该给您-在两点的情况下-连接两点的弧的中点。