【问题标题】:MySQL function ST_Distance_Sphere isn't using Haversine formula?MySQL 函数 ST_Distance_Sphere 没有使用 Haversine 公式?
【发布时间】:2021-06-15 17:01:08
【问题描述】:

我正在尝试使用 MySQL 计算两个地理点之间的距离,但我认为 ST_Distance_Sphere 函数不正确或未使用 Haversine 公式。

为了描述这个问题,我将使用这两个点和这个地球半径:

Point A: 41.8902142, 12.4900422
Point B: 48.8583736, 2.2922926
Earth radius: 6378000

我在 JavaScript 中使用 Haversine 公式制作了这个脚本:

Number.prototype.toRad = function() {
    return this * Math.PI / 180;
}

const sin2 = (x) => {
    return Math.pow( Math.sin(x), 2 );
}

 function computeDistanceBetween(x1, y1, x2, y2, rad = 6378000) {
            
    const x_diff = x2 - x1;
    const y_diff = y2 - y1;

    let a = sin2(x_diff.toRad() / 2) + Math.cos(x1.toRad()) * Math.cos(x2.toRad()) * sin2(y_diff.toRad() / 2);

    a = 2 * rad * Math.asin(Math.sqrt(a))

    return a;

}

console.log(

    computeDistanceBetween(
        41.8902142, 12.4900422,
        48.8583736, 2.2922926
    ) / 1000 // Convert to Km
    
);

这个脚本给了我这个结果:1110.6415064d524447,如果我在谷歌地图中检查,结果大致相同 (1,109.43 km)

现在,MySQL 是问题所在,我正试图对这两点做同样的事情,但结果却大不相同:

SELECT 
ST_Distance_Sphere(
    POINT(41.8902142, 12.4900422), POINT(48.8583736, 2.2922926), 6378000
) / 1000 as distances

结果给我1370.65792958018,有260公里的差异,所以结果很错误,注意我在两种情况下都使用完全相同的点和相同的半径,所以MySQL是错误的或什么的?如何获得与 JavaScript 相同的结果,但在 MySQL 中使用空间函数?非常感谢您的帮助

【问题讨论】:

    标签: mysql distance haversine spatial-query


    【解决方案1】:

    好的,这很棘手,函数POINT首先接收longitude参数,然后接收latitude参数,所以,正确的查询应该是这样的:

    SELECT 
    ST_Distance_Sphere(
        POINT(12.4900422, 41.8902142), POINT(2.2922926, 48.8583736), 6378000
    ) / 1000 as distances
    

    所以这返回给我1110.641506452445 这是正确的?

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 2010-10-09
      • 2020-04-09
      • 2011-06-20
      • 2018-12-11
      • 2013-01-11
      相关资源
      最近更新 更多