我正在使用Cordova应用程序,我使用不同的AngularJs状态。 如果我在第一个状态geolocation.watchposition中调用它完美,但如果我在第二个状态调用它,我会被拒绝访问...
我用Button更改状态。无论我先开始哪个州,第一个有GPS,第二个没有。
编辑:我应该提一下,它在浏览器中工作,但不在我的Android设备上。
你知道为什么吗?
index.js
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
templateUrl: 'templates/main_menu.html',
controller: 'AppCtrl'
})
.state('map', {
url: '/map',
templateUrl: 'templates/map.html',
controller: 'MapCtrl'
});
//First State
$urlRouterProvider.otherwise('/app');
});
controller.js
.controller('AppCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window) {
$scope.accPos = function () {
var id, target, options;
function success(pos) {
alert("Pos: " + pos.coords.latitude + " " + pos.coords.longitude);
}
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
}
options = {
enableHighAccuracy: false,
timeout: 6000,
maximumAge: 0
};
id = navigator.geolocation.watchPosition(success, error, options);
};
$scope.accPos();
}
//Looks exactly the same
.controller('MapCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window) { ... }
答案 0 :(得分:1)
您应该将此类代码移动到服务中,以便可以在控制器之间共享。最重要的是,您可以利用ui-router的resolve功能来解析每个需要它的州的GPS位置。
例如:
service.js
.factory('GeoLocationService', function ($window) {
var id, target, options, lastPosition;
options = {
enableHighAccuracy: false,
timeout: 6000,
maximumAge: 0
};
var geoLocationService = {
startWatching: startWatching,
stopWatching: stopWatching,
getLastPosition: getLastPosition,
options: options
};
startWatching();
return geoLocationService;
function getLastPosition() {
return lastPosition;
}
function startWatching() {
id = $window.navigator.geolocation.watchPosition(success, error, options);
}
function stopWatching() {
$window.navigator.geolocation.clearWatch(id);
}
function success(pos) {
lastPosition = pos;
alert("Pos: " + pos.coords.latitude + " " + pos.coords.longitude);
}
function error(err) {
alert('ERROR(' + err.code + '): ' + err.message);
}
});
index.js
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
templateUrl: 'templates/main_menu.html',
controller: 'AppCtrl',
resolve: {
location: function(GeoLocationService){
return GeoLocationService.getLastPosition();
}
}
})
.state('map', {
url: '/map',
templateUrl: 'templates/map.html',
controller: 'MapCtrl',
resolve: {
location: function(GeoLocationService){
return GeoLocationService.getLastPosition();
}
}
});
//First State
$urlRouterProvider.otherwise('/app');
});
controller.js
.controller('AppCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window, GeoLocationService, location) {
// show the location at start
alert("Pos: " + location.coords.latitude + " " + location.coords.longitude);
// maybe watch the location from the service
$scope.$watch(function () {
return GeoLocationService.getLastPosition();
},
function (newValue, oldValue) {
if (newValue !== oldValue) {
// do something
}
}, true);
}
请注意,此代码完全未经测试。我只是试图了解这个想法。
干杯!