【问题标题】:Haversine formula not working correctlyHaversine 公式无法正常工作
【发布时间】:2014-08-15 17:37:12
【问题描述】:

这是我基于thisthis question 的答案的Haversine 公式代码:

$scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
        var lat2 = 41.894993;
        var lon2 = -88.459239;
        var lat1 = $scope.locLat;
        var lon1 = $scope.locLon;

        var R = 3959;
        var x1 = lat1 - lat2;
        var dLat = x1 * Math.PI / 180;
        var x2 = lon1 - lon2;
        var dLon = x2 * Math.PI / 180;
        var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
          Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
          Math.sin(dLon / 2) * Math.sin(dLon / 2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        d = R * c;
        return d;
    }

我用 3 个不同的位置对此进行了测试,它们都相距甚远,第一个位置表示其距离为 14790.7 英里,而实际距离为 44.1 英里,每个位置的偏差量都不同。有些是少量的,有些是非常大的。我的数学有问题吗?如果没有,为什么这段代码不能正常工作? 这是我完整项目的链接:http://plnkr.co/edit/nRQc7Ym0lsaK6jQwd626?p=preview
非常感谢您的帮助!!!

【问题讨论】:

    标签: javascript angularjs object coordinates haversine


    【解决方案1】:

    实际计算出距离。问题在于你如何在你的函数中使用它。

    您在函数myLat, myLon, locLat, locLon 中传递了4 个参数,然后不使用它们。我假设您仍在 forEach 循环中调用函数。试试这个

    外面forEach

    var myLat = 41.894993;
    var myLon = -88.459239;
    

    内部forEach

    var locLat = $scope.locLat;
    var locLon = $scope.locLon;
    getCoordDistance(myLat, myLon, locLat, locLon)
    etc.
    

    功能

    $scope.getCoordDistance = function (myLat, myLon, locLat, locLon) {
           var R = 3959;
            var x1 = lat1 - lat2;
            var dLat = x1 * Math.PI / 180;
            var x2 = lon1 - lon2;
            var dLon = x2 * Math.PI / 180;
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            d = R * c;
            return d;
        }   
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 2016-04-03
      相关资源
      最近更新 更多