javascript - Phonegap/AngularJS : Get lat/long from inside function

标签 javascript angularjs cordova

我正在尝试从函数内部设置几个全局变量,以便我可以在 Angular Ctrl 中使用结果。

我已经尝试了我能想到的一切,但似乎无法在函数之外获取变量。我知道这可能很简单,但就是无法弄清楚!

预先感谢您的帮助。

onSuccess = function(position) {

        lat = position.coords.latitude;
        lon = position.coords.latitude;
        // alert('Latitude: '          + position.coords.latitude          + '\n' +
        //       'Longitude: '         + position.coords.longitude         + '\n' +
        //       'Altitude: '          + position.coords.altitude          + '\n' +
        //       'Accuracy: '          + position.coords.accuracy          + '\n' +
        //       'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
        //       'Heading: '           + position.coords.heading           + '\n' +
        //       'Speed: '             + position.coords.speed             + '\n' +
        //       'Timestamp: '         + new Date(position.timestamp)      + '\n');
    };

    // onError Callback receives a PositionError object
    //
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    // ??????
    console.log(getCurrentPosition.lat);

编辑:这是 Controller

我需要获取纬度和经度来代替当前的硬编码版本:

var app = angular.module('presto-map', ["ngResource", "ngSanitize", "google-maps"]);

    function mapCtrl ($scope) {

        // Initialise the map
        $scope.map = {
            center: {
                latitude: 53.58684546368308,
                longitude: -1.5543620512747744
            },
            zoom: 8
        };

    }

最佳答案

$window 传递到您的 Controller 并在您的范围内设置 lat lng

       $scope.getCurrentLocation = function () {
            $window.navigator.geolocation.getCurrentPosition(function(position) {
                $scope.$apply(function() {
                    $scope.latitude = position.coords.latitude;
                    $scope.longitude = position.coords.longitude;
                    $scope.accuracy = position.coords.accuracy;
                });
                }, function(error) {
                    alert(error);
            });
        }

否则,如果您想在应用程序中使用一些全局变量,请使用服务来执行此操作。在服务中拥有所有全局数据,然后通过将服务传递给 Controller ​​来在 Controller 中访问它。

关于javascript - Phonegap/AngularJS : Get lat/long from inside function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21237603/

相关文章:

javascript - 减少 Javascript CPU 使用率

javascript - ng-click <tr> 不执行任何操作

javascript - 追加函数不返回追加的对象吗?

javascript - Angular, "activate"数据传入后的 watch

gwt - 大型 GWT Web 应用程序有哪些移动支持选项?

javascript - backbone js 对我的联系人列表进行排序

javascript - HTML canvas drawImage 不能正常用于横向图像

javascript - 当我更改语言时, Angular 翻译不会刷新 Controller 中的翻译

ios - cdvfile ://不支持的 URL 错误

iphone - iOS Phone Gap/Cordova 2.2.0 中的默认启动图像