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

tyl*_*hes 3 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 );
};
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*lov 8

首先,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;
});
Run Code Online (Sandbox Code Playgroud)

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

navigator.geolocation.getCurrentPosition( function(position) {
    this.coordinates.latitude = position.coords.latitude;
    this.coordinates.longitude = position.coords.longitude;
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

我的解决方案

最好将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();
};
Run Code Online (Sandbox Code Playgroud)

如何使用它

var userPositionPromise = getCurrentPosition();

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

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