2

我正在尝试打印显示其名称以及其与用户位置之间的距离的对象列表。我确实通过 GET 检索数据并根据纬度和经度计算距离。但是,我的作用域数组的长度仍然为 0。我想我的回调架构有问题,但我似乎无法弄清楚。

控制器:

angular.module('ionicApp', ['ionic']).controller('objectCtrl', function($scope, $http) {
$scope.objects = [];
$http.get('http://url.com/getobjects.php').then(function (resp) {
    for (var i = 0; i < resp.data.length; i++) {
        getDistance(resp.data[i].lat, resp.data[i].lng, (function(index){
            return function(dist){
                $scope.objects[index] = {
                    name: resp.data[index].name,
                    distance: dist
                };
            }
        })(i));
    }
}, function (err) {
    console.error('ERR', err);
    alert("error");
});

获取距离:

function getDistance(lat2, lon2, callback) {
    navigator.geolocation.getCurrentPosition(function onSuccess(position) {
        var lat1 = position.coords.latitude;
        var lon1 = position.coords.longitude;
        var radlat1 = Math.PI * lat1 / 180;
        var radlat2 = Math.PI * lat2 / 180;
        var radlon1 = Math.PI * lon1 / 180;
        var radlon2 = Math.PI * lon2 / 180;
        var theta = lon1 - lon2;
        var radtheta = Math.PI * theta / 180;
        var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        dist = Math.acos(dist);
        dist = dist * 180 / Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344;
        callback(dist);
    }, function onError(error) {
        alert("no location found:"+ error);
    });
}

任何想法我的代码有什么问题?谢谢。

4

2 回答 2

1

看起来getDistance回调出现在 $digest 循环之外。所以你应该尝试手动启动它:

$scope.objects[index] = {
    name: resp.data[index].name,
    distance: dist
};
$scope.$apply();

或使用$timeout服务:

getDistance(resp.data[i].lat, resp.data[i].lng, (function (index) {
    return function (dist) {
        $timeout(function() {
            $scope.objects[index] = {
                name: resp.data[index].name,
                distance: dist
            };
        });
    }
})(i));
于 2014-10-17T11:57:36.927 回答
0

代替

        $scope.objects[index] = {
            name: resp.data[index].name,
            distance: dist
        };

代替

        $scope.objects.push({
            name: resp.data[index].name,
            distance: dist
        });
于 2014-10-17T11:58:37.417 回答