如何使用HTML5 Geolocation API实现promise?

Pio*_*cki 3 javascript api ajax jquery geolocation

我怎么能纠正下面的代码,以便它不返回函数的undefined值getPreciseLocation?

总之,当用户点击#precise-location-prompt并与浏览器共享位置时,应该有一个AJAX调用来获取当前天气.但是,此时undefined用户点击后会立即出现值错误#precise-location-prompt.

// Get weather data for the current location
function getCurrentWeather(coordinates) {
  return $.ajax('http://www.example.com/lat=' + coordinates[0] + '&lon=' + coordinates[1]);
}

// Show weather in DOM
function showCurrentWeather(data) {
  var currentTemperature = data.temperature;
  $('#current-temperature').text(currentTemperature);
}

// Get precise location based via the Geolocation API
function getPreciseLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(displayPosition, displayError);
  } else {
    console.log("Geolocation is not supported by this browser");
  }
}

// Success function for the Geolocation API
function displayPosition(position) {
  return [position.coords.latitude, position.coords.longitude];
}

// Error function for the Geolocation API
function displayError(error) {
  console.log('Precise location is not available at the moment.');
}

// Promises chain with the AJAX requests
function getWeatherWrapper() {
  return getPreciseLocation().then(function(locationData) {
    return getCurrentWeather(locationData);
    }).then(function(weatherData) {
      return showCurrentWeather(weatherData);
    });
}

// User's interaction with the website
$('#precise-location-prompt').on('click', getWeatherWrapper);
Run Code Online (Sandbox Code Playgroud)

And*_*ndy 10

这个演示使用JSfiddle AJAX方法(奇怪的是,使用Mootools)来模拟请求但你可以在$.ajax方法中替换.我还将jQuery的其余部分替换为此测试的vanilla JS事件侦听器和选择器,但您可以非常轻松地将它们添加回代码中.

返回一个在success回调中解析的新promise .

function getCurrentWeather(coordinates) {
  return new Promise(function (resolve, reject) {
    new Request.JSON({
      url: '/echo/json/',
      data: {
        json: JSON.encode({ temperature: 'Too hot!' }),
        delay: 1
      },
      onSuccess: function (response) {
        resolve(response);
      }
    }).send();
  });
}

function showCurrentWeather(data) {
  var temp = document.getElementById('current-temperature');
  temp.textContent = data.temperature;
}
Run Code Online (Sandbox Code Playgroud)

返回displayPosition在调用原始内容时解析的承诺.我重新添加了该功能,getPreciseLocation因为它更容易让它工作.您还可以在此处添加回检查地理位置,并reject根据需要添加.

function getPreciseLocation() {
  return new Promise(function (resolve, reject) {
    navigator.geolocation.getCurrentPosition(function (position) {
      resolve([position.coords.latitude, position.coords.longitude]);
    });
  });
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们只需减少代码占用空间,即可使用适当的数据调用相关函数.

function getWeatherWrapper() {
  getPreciseLocation()
    .then(getCurrentWeather)
    .then(showCurrentWeather);
}

var prompt = document.getElementById('precise-location-prompt');
prompt.addEventListener('click', getWeatherWrapper);
Run Code Online (Sandbox Code Playgroud)

DEMO