1

ファクトリへの呼び出しが、マップ コントローラーですぐに返されます。マップの中心を設定しようとしていますが、geo の呼び出しが undefined を返すため、中心が設定されません。ただし、座標はジオ ファクトリで取得されます。彼らは遅すぎます。

.then() のポイントは、日付が返されるのを待つことだと思いました。では、アプリを強制的に待機させるにはどうすればよいでしょうか?

私の工場は:

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
};});

私のマップコントローラーは次のように呼び出します:

// GEOLOCATION
geo.getPosition().then( function (position) {
    console.log(position);
    $scope.center.lat = position.latitude;
    $scope.center.lon = position.longitude;
});
4

1 に答える 1

0

geolocation.getCurrentPosition が返される前に deferred.resolve を呼び出しています。次の後に呼び出す必要があります。

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;
}

動作中の plunkr は次のとおりです: http://plnkr.co/edit/H7LEjsrSkZOzGBZIeTXF?p=preview

于 2015-07-28T17:50:32.450 に答える