gpt4 book ai didi

javascript - 如何使用 HTML5 Geolocation API 实现 promise ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:19 24 4
gpt4 key购买 nike

如何更正下面的代码,使其不会为 getPreciseLocation 函数返回 undefined 值?

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

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

最佳答案

此演示使用 JSfiddle AJAX 方法(奇怪的是,它使用 Mootools)来模拟请求,但您可以替换为 $.ajax 方法。我还用 jQuery 的其余部分替换了此测试的原始 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;
}

返回一个在您的原始 displayPosition 被调用时解析的 promise 。我将该函数添加回 getPreciseLocation 中,因为它更容易工作。您还可以在此处重新添加对地理位置的检查,并在您认为合适的情况下添加拒绝

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

这里我们只是减少代码占用空间,以使用适当的数据调用相关函数。

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

var prompt = document.getElementById('precise-location-prompt');
prompt.addEventListener('click', getWeatherWrapper);

DEMO

关于javascript - 如何使用 HTML5 Geolocation API 实现 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36995628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com