构建我的应用程序,以便控制器中可以使用lat和long coords

时间:2016-12-04 20:40:31

标签: angularjs cordova ionic-framework

我有一个控制器,其中包含以下代码。我发现在下面的代码返回之前我的其余代码都在运行。

如何最好地构建我的代码,以便lat和long coords可用于控制器中的其余代码?

我想我可以将下面的代码放在运行块中,并将lat和long分配给$rootScope,但我不想这样做。

$ionicPlatform.ready(function() {
var self = this;
  $cordovaGeolocation.getCurrentPosition({timeout: 10000, enableHighAccuracy: true}).then(
  function(position){
    self.latitude1 = position.coords.latitude;
    self.longitude1 = position.coords.longitude;
    console.log(position.coords.latitude);
    console.log(position.coords.longitude);
  },
  function(error){
    console.log(error);
  });
});

欢迎任何建议。

2 个答案:

答案 0 :(得分:2)

保存承诺:

var positionPromise = $ionicPlatform.ready()
    .then (function() {
         //return to chain
         return $cordovaGeolocation.getCurrentPosition(config);
    }).catch (function (error) {
         console.log(error);
         //throw to chain error
         throw error;
    });

在其他地方,使用承诺:

positionPromise.then(function (position) {
    console.log(position);
    //PUT delayed code here
    //...
}).catch(function (error) {
    console.log(error);
});

答案 1 :(得分:0)

使用上面的答案,我得到了这个:

app.factory('geoService', function($ionicPlatform, $cordovaGeolocation) {

  var positionOptions = {timeout: 10000, enableHighAccuracy: true};

  return {
    getPosition: function() {
      return $ionicPlatform.ready()
        .then(function() {
          return $cordovaGeolocation.getCurrentPosition(positionOptions);
        })
    }
  };
});

然后将工厂注入我的控制器并使用它:

geoService.getPosition()
  .then(function(position) {
    // code the depends on the position coords.
  })