我的Service.js
appnService.factory('LocationService', function(){
var currentLocation = {
latitude:"",
longitude:""
}
return {
GetLocation : function(){
return navigator.geolocation.getCurrentPosition(function(pos){
currentLocation.latitude = pos.coords.latitude;
currentLocation.longitude= pos.coords.longitude;
return currentLocation;
});
}
};
});
我的控制器
appne.controller('NewObservationCtrl',function($scope,$state,LocationService) {
LocationService.GetLocation().then(function(data){
console.log(data);
});
});
但我得到了错误
TypeError:无法读取属性'然后'在控制器中未定义
请帮忙
答案 0 :(得分:3)
navigator.geolocation.getCurrentPosition(function() {})
返回undefined
。如果您需要承诺,则必须使用位置值
.factory('LocationService', function ($q) {
var currentLocation = {
latitude: "",
longitude: ""
}
return {
GetLocation: function () {
var d = $q.defer();
navigator.geolocation.getCurrentPosition(function (pos) {
currentLocation.latitude = pos.coords.latitude;
currentLocation.longitude = pos.coords.longitude;
d.resolve(currentLocation);
});
return d.promise
}
};
});