0

I have made a LocationService in angularjs

factory('LocationService', function ($q) {
    var deferred = $q.defer();
    var curPos = {};
    var resolved = false;

    return {
        getPosition : function (refresh) {
            if (!resolved || refresh) {
                navigator.geolocation.getCurrentPosition(function (pos) {
                    curPos.curLat = pos.coords.latitude;
                    curPos.curLng = pos.coords.longitude;
                    resolved = true;
                    console.log("Resolve", curPos);
                    deferred.resolve(curPos);
                }, function (error) {
                    deferred.reject('Unable to get location: ' + error.message);
                }, {
                    enableHighAccuracy : true
                });
            } else {
                deferred.resolve(curPos);
            }
            return deferred.promise;
        }
    }
})

and using it like this

LocationService.getPosition(refresh).then(function (curPos) {
    console.log('then');
    var latLng = new google.maps.LatLng(curPos.curLat, curPos.curLng);
    $scope.map.setCenter(latLng);
    $scope.map.setZoom(15);
});

First time it works fine, but when I click a button which calls getPosition(), it resolves even before the LocationService triggers deferred.resolve(). and I get the wrong result in the callback. But eventually after 2/3 seconds getCurrentPosition fires callback and the new value is set in curPos. Which I get for the next time.

The console prints then first and Resolve after 2/3 seconds.

I am not able to understand what's wrong here. Could someone guide a bit?

6
  • Are you trying to cache data? then you should use $cacheFactory
    – Satpal
    Aug 30, 2014 at 13:06
  • Yes, I want to refresh user location only if I pass refresh explicitly.
    – Salman
    Aug 30, 2014 at 13:07
  • Ok, will have a look at that. But that's not the problem here, is it?
    – Salman
    Aug 30, 2014 at 13:09
  • 2
    Not sure, Move var deferred = $q.defer(); inside your function
    – Satpal
    Aug 30, 2014 at 13:19
  • 1
    OOO! Exactly, that was the problem. Why didn't I think of this. keeping it outside preserves its resolved state from previous call, due to which then gets called immediately. Thanks a ton!!
    – Salman
    Aug 30, 2014 at 13:22

1 Answer 1

0

Your deferred gets declared as part of the service construction. Once your first call to getPosition finishes, that deferred gets resolved. You need to create and use a new deferred for each call to getPosition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.