使地理定位坐标可用于其他功能

时间:2016-02-09 04:57:31

标签: javascript geolocation

我正在开发一个基本的JavaScript天气应用程序。我想从浏览器中提取地理位置,并使其可以访问我的其他功能。

function Weather( options ) {

    this.apiKey = options.key;
    this.endpoint = options.endpoint;
    this.coordinates = {};
}

Weather.prototype.GetLocation = function( callback ) {
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition( function(position) {
            this.coordinates.latitude = position.coords.latitude;
            this.coordinates.longitude = position.coords.longitude;
        });
    }
};

Weather.prototype.GetCurrentConditions = function() {

    this.GetLocation();

    var url = this.endpoint + "weather?lat=" + this.coordinates.latitude + "&lon=" + this.coordinates.longitude;

    return this.getJSONP( url );
};

Weather.prototype.GetExtendedForecast = function() {

    this.GetLocation();

    var url = this.endpoint + "forecast/daily?lat=" + this.coordinates.latitude + "&lon=" + this.coordinates.longitude + "&cnt=7";

    return this.getJSONP( url );
};

然而,我一直不确定为我的经纬度。我读到某个地方,如果你想使用你需要的坐标将它们保存在getCurrentPosition的回调函数中,这就是我所做的,但我仍然无法获得除undefined之外的任何东西。有没有办法让我的其他函数可以访问这些值?

1 个答案:

答案 0 :(得分:7)

首先navigator.geolocation.getCurrentPosition回调异步工作,因此您在调用this.GetLocation()后无法立即获得结果。此外,用户可以禁止与应用程序共享其位置。

其次this出错了。您需要在此处将上下文传递给回调:

navigator.geolocation.getCurrentPosition( function(position) {
    // "this" doesn't equal to instance of your Weather class
    this.coordinates.latitude = position.coords.latitude;
    this.coordinates.longitude = position.coords.longitude;
});

例如,您可以使用.bind(this)将预期的上下文传递给回调:

navigator.geolocation.getCurrentPosition( function(position) {
    this.coordinates.latitude = position.coords.latitude;
    this.coordinates.longitude = position.coords.longitude;
}.bind(this));

我的解决方案

最好将Promise用于异步代码。您可以使用Promise的任何实现,我更喜欢JQuery.deferred

我的代码是:

var getCurrentPosition = function() {
  var deferred = $.Deferred();

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(deferred.resolve, deferred.reject);
  } else {
    deferred.reject({
      error: 'browser doesn\'t support geolocation'
    });
  }

  return deferred.promise();
};

如何使用

var userPositionPromise = getCurrentPosition();

userPositionPromise
  .then(function(data) {
    // do whatever you want with geolocation data
  })
  .fail(function(error) {
    // show error for user
  });

您可以根据需要使用userPositionPromise,它将作为用户位置数据的容器,您无需再次调用getUserPosition。要访问数据,您需要为.then(callback)变量调用userPositionPromise

相关问题