Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  41] [ 1]  / answers: 1 / hits: 16058  / 11 Years ago, tue, july 16, 2013, 12:00:00

I have a service like



app.factory('geolocation', function ($rootScope, cordovaReady) {
return {
getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {

navigator.geolocation.getCurrentPosition(function () {
var that = this,
args = arguments;

if (onSuccess) {
$rootScope.$apply(function () {
onSuccess.apply(that, args);
});
}
}, function () {
var that = this,
args = arguments;
if (onError) {
$rootScope.$apply(function () {
onError.apply(that, args);
});
}
}, options);
}),
getCurrentCity: function (onSuccess, onError) {
this.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode(options,function (results, status) {
var city = address_component.long_name;
});
});
}
}
});


And I want to do from a controller something like



function MainCtrl($scope, geolocation) {
geolocation.getCurrentCity(function(city){
$scope.city = city;
});
};


The getCurrentPosition works fine and the city is determined too, however I don't know how to access the city in controller.



What happens? When getCurrentCity is called, it calles getCurrentPosition to determine the gps coords. This coords are passed as arguments to the onSuccess method right? So this is quite the same I want to do in the getCurrentCity method, but I don't know how. Ones the async geocoder retrieved the city, I want to apply the new data to the onSuccess method.



Any ideas?


More From » angularjs

 Answers
11

You are dealing with callbacks and asynchronous request. So you should use $q service. Just inject it in your service with $rootScope and cordovaReady dependency.
And add the promises to your function like this



getCurrentCity: function () {
var deferred = $q.defer();
this.getCurrentPosition(function (position) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode(options,function (results, status) {
var city = address_component.long_name;
$rootScope.$apply(function(){
deferred.resolve(city);
});
});
});
return deferred.promise;
}


And in your controller, do the following to handle the promise.



function MainCtrl($scope, geolocation) {
geolocation.getCurrentCity().then(function(result) { //result === city
$scope.city = result;
//do whatever you want. This will be executed once city value is available
});
};

[#76956] Monday, July 15, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;