Ionic + ngCordova +背景地理位置+ DeviceReady问题

问题描述 投票:0回答:1

我正在尝试让后台地理位置插件在我的应用中正常工作;但是,仅当我使用deviceready功能时,页面有时才加载到我的设备上。从我的谷歌搜索看来,我应该改用$ionicPlatform.ready,但是当我尝试使用$cordovaBackgroundGeolocation时却未定义。同样,当我尝试对其进行任何操作时,该设备始终是未定义的。

我还尝试过手动引导角度,这没有用;我试着简单地运行该函数,而不将其放入deviceready$ionicPlatform.ready或其他任何内容中;那也不起作用。

相关代码:

控制器:

// Define the angular module
angular.module('testApp.controllers', ['ionic', 'ngCordova.plugins.geolocation', 'ngCordova.plugins.backgroundGeolocation'])

.controller('MapCtrl', ['$scope', '$ionicPopup', '$cordovaGeolocation', '$cordovaBackgroundGeolocation', '$timeout', '$http', '$ionicPlatform', 
               function ($scope, $ionicPopup, $cordovaGeolocation, $cordovaBackgroundGeolocation, $timeout, $http, $ionicPlatform) {
    $scope.loaded = false;

    var posOptions = { timeout: 5000, enableHighAccuracy: true, maximumAge: 5000 };
    $cordovaGeolocation.getCurrentPosition(posOptions)
        .then(function (location) {
            $scope.currentLat = location.coords.latitude;
            $scope.currentLong = location.coords.longitude;
            $scope.loaded = true;
        });

    $ionicPlatform.ready(function() {
        var bgGeo = $cordovaBackgroundGeolocation;

        // BackgroundGeoLocation is highly configurable.
        bgGeo.configure({
            url: 'http://www.my_api_url_here/',
            params: {
                deviceId: "testApp",
                "location": {
                    "latitude": "38.896339999999995",
                    "longitude": "-77.08521460000001"
                }
            },
            desiredAccuracy: 10,
            stationaryRadius: 20,
            distanceFilter: 30,
            notificationTitle: 'TestTitle', // <-- android only, customize the title of the notification
            notificationText: 'TestText', // <-- android only, customize the text of the notification
            activityType: 'OtherNavigation',
            debug: true, // <-- enable this hear sounds for background-geolocation life-cycle.
            stopOnTerminate: false // <-- enable this to clear background location settings when the app terminates
        });

        bgGeo.start();
    });
}])

指令:

.directive('bgeo', ['$cordovaGeolocation', '$cordovaBackgroundGeolocation', '$http', 
           function ($cordovaGeolocation, $cordovaBackgroundGeolocation, $http) {
    return {
        scope: {
           lat: '=',
           lng: '='
       },
        link: function (scope) {
            console.log("directive: ", scope.lat, scope.lng);
                myLatLng = new google.maps.LatLng(scope.lat, scope.lng);
                mapOptions = {
                    zoom: 16,
                    center: myLatLng
                };
                map = new google.maps.Map(document.getElementById('map'), mapOptions);
                marker = new google.maps.Marker({
                    position: myLatLng,
                    map: map,
                    draggable: false,
                    icon: 'small-orange-pin.png'
                });
        }
    }
}])

模板:

<ion-scroll zooming="true" direction="xy" style="width:90%">
   <div ng-if="loaded" bgeo lat="currentLat" lng="currentLong">
       <div id="map" style="width: 600px; height: 500px;"></div>
   </div>
</ion-scroll>

app.js运行方法:

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }

    if (window.cordova) {
      if (window.plugins && window.plugins.backgroundGeoLocation) {
        BackgroundGeolocation.configurePlugin(window.plugins.backgroundGeoLocation);
      }
    }
  });
})

完整的源代码在github上的https://github.com/sahiltalwar88/binding-geolocation-issue。非常感谢您的帮助!

angularjs ionic-framework cordova-plugins
1个回答
1
投票

主要问题是我必须运行Bower安装;我缺少几个包裹。一旦这样做,我就可以使用ionic ready函数和onDeviceReady了。然后,为了使iOS回调函数正常工作,我不得不更新语法以使其与ngCordova(使用Q和Promise)一起使用,而不是像示例所示那样使用回调函数。

这是我最终代码的结构:

$ionicPlatform.ready(function() {
if(window.StatusBar) {
  StatusBar.styleDefault();
}

$location.path('/app');
$rootScope.$digest();

$rootScope.deviceReady = false; 

document.addEventListener('deviceready', function () {
    if(window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }

    var bgGeo = $cordovaBackgroundGeolocation;
    var deviceId = $cordovaDevice.getUUID();
    var addVisitUrl = 'your-url-goes-here';

    $rootScope.deviceId = deviceId;
    $rootScope.deviceReady = true;

    var posOptions = { timeout: 5000, enableHighAccuracy: true, maximumAge: 5000 };
    $cordovaGeolocation.getCurrentPosition(posOptions)
        .then(function (location) {
            $rootScope.currentLat = location.coords.latitude;
            $rootScope.currentLong = location.coords.longitude;

            var yourAjaxCallback = function(response) {
                bgGeo.finish();
            };

            var callbackFn = function(location) {
                var data = {
                                deviceId: deviceId,
                                "location": {
                                    "latitude": location.latitude,
                                    "longitude": location.longitude
                                }
                            };
                $http.post(addVisitUrl, data);
                // Other code goes here

                yourAjaxCallback.call(this);
            };

            var failureFn = function(error) {
                alert('Background Geolocation Error: ' + error);
                // Other code goes here
            };

            bgGeo.configure({
                url: addVisitUrl,
                params: {
                    deviceId: deviceId,
                    "location": {
                        "latitude": $rootScope.currentLat,
                        "longitude": $rootScope.currentLong
                    }
                },
                desiredAccuracy: 10,
                stationaryRadius: 10,
                distanceFilter: 10,
                activityType: 'OtherNavigation',
                debug: true, 
                stopOnTerminate: false
            })
            .then(callbackFn, failureFn, callbackFn);

            bgGeo.start();
        });
    $rootScope.$digest();
    });
  });
})
© www.soinside.com 2019 - 2024. All rights reserved.