角度:两个位置之间的距离

时间:2018-05-20 10:36:54

标签: angularjs

我有两个位置坐标。我需要检查两个坐标之间的距离。我在PHP,C ++,C#和Java中搜索并找到了一些代码。

我正在使用Angular1,我需要在客户端进行计算。所以,我正在寻找Angular的帮助。这是用JavaScript编写的代码,我需要将其转换为Angular。

    function degreesToRadians(degrees) {
                                return degrees * Math.PI / 180;
                              }

                              function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
                                var earthRadiusKm = 6371;


var dLat = degreesToRadians(lat2-lat1);
                        var dLon = degreesToRadians(lon2-lon1);

                        lat1 = degreesToRadians(lat1);
                        lat2 = degreesToRadians(lat2);

                        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                                Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
                        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
                        return earthRadiusKm * c;
                      }

问题是我从未在Angular中创建过一个函数。我怎么开始呢?

我试过这个

$scope.distance = distanceInKmBetweenCoordinates($scope.userlatitude, $scope.userlongitude, $scope.mylatitude, $scope.mylongitude);

 alert($scope.distance);

它给了我错误:

  

ReferenceError:distanceInKmBetweenCoordinates未定义

1 个答案:

答案 0 :(得分:2)

在您的控制器中:

function degreesToRadians(degrees) {
        return degrees * Math.PI / 180;
    }

function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) {
        var earthRadiusKm = 6371;

        var dLat = degreesToRadians(lat2-lat1);
        var dLon = degreesToRadians(lon2-lon1);

        lat1 = degreesToRadians(lat1);
        lat2 = degreesToRadians(lat2);

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        return earthRadiusKm * c;
}

$scope.distance = distanceInKmBetweenEarthCoordinates($scope.userlatitude, $scope.userlongitude, $scope.mylatitude, $scope.mylongitude);
alert($scope.distance);