1

My call to the factory returns too quickly in my map controller. I am trying to set the centre of the map however since the call to geo returns undefined it never sets centre. However the coordinates are grabbed in the geo factory. They are just too late.

I thought the point of .then() was to wait for the date to be returned. So, how do I force my app to wait?

My factory is:

angular.module('comhubApp')
.factory('geo', function ($q) {

var getPosition = function () {
    var deferred = $q.defer();
    if (navigator.geolocation) {
      deferred.resolve(navigator.geolocation.getCurrentPosition(function (position) {
        var crd = position.coords;
        console.log('Latitude : ' + crd.latitude);
        console.log('Longitude: ' + crd.longitude);
        return crd;
      } ));
    }
    return deferred.promise;
}

// Public API here
return {
  getPosition: getPosition
};});

My map controller calls it with:

// GEOLOCATION
geo.getPosition().then( function (position) {
    console.log(position);
    $scope.center.lat = position.latitude;
    $scope.center.lon = position.longitude;
});
sitrucj
  • 118
  • 13
  • .then will only wait for data to be returned if teh function passed to it returns a thenable. In your case you aren't even giving it a function, instead you're giving it `undefined`. – Kevin B Jul 28 '15 at 17:27
  • I see that the function is returning position as undefined. I am just not sure why. I thought my code was supposed to wait on deferred.promise to return the data from getPostion but I am obviously wrong, which is why I am on here. – sitrucj Jul 28 '15 at 17:51
  • It isn't returning position as undefined, the function itself ALWAYS returns undefined because that is what it is designed to do. – Kevin B Jul 28 '15 at 18:01

1 Answers1

0

You are calling deferred.resolve before geolocation.getCurrentPosition has returned. You need to call it after:

var getPosition = function() {
  var deferred = $q.defer();
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var crd = position.coords;
      console.log('Latitude : ' + crd.latitude);
      console.log('Longitude: ' + crd.longitude);
      deferred.resolve(crd);
    });
  }
  return deferred.promise;
}

Here's a working plunkr: http://plnkr.co/edit/H7LEjsrSkZOzGBZIeTXF?p=preview

yvesmancera
  • 2,915
  • 5
  • 24
  • 33
  • I just came on here to put that up! What a mess. You rock! I ended up going with `navigator.geolocation.getCurrentPosition(function (position) { deferred.resolve(position); });` That way I can do more with it in the future if needed. – sitrucj Jul 28 '15 at 17:59
  • No problem, glad I could help! – yvesmancera Jul 28 '15 at 18:00