Javascript 如何使用HTML5地理定位API实现承诺?
如何更正下面的代码,使其不返回Javascript 如何使用HTML5地理定位API实现承诺?,javascript,jquery,ajax,api,geolocation,Javascript,Jquery,Ajax,Api,Geolocation,如何更正下面的代码,使其不返回getprecisselocation函数的undefined值 总之,当用户单击#精确位置提示符并与浏览器共享位置时,应该有一个AJAX调用来获取当前天气。但是,在用户单击#精确位置提示符后,立即出现未定义的值错误 // Get weather data for the current location function getCurrentWeather(coordinates) { return $.ajax('http://www.example.com
getprecisselocation
函数的undefined
值
总之,当用户单击#精确位置提示符
并与浏览器共享位置时,应该有一个AJAX调用来获取当前天气。但是,在用户单击#精确位置提示符
后,立即出现未定义的
值错误
// 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的其余部分替换了vanilla JS事件监听器和选择器,但是您可以很容易地将它们添加回代码中
返回在success
回调中解析的新承诺
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
时解析的承诺。我将该函数重新添加到getprecisselocation
中,因为它更容易工作。您还可以在此处添加回您的地理位置检查,以及您认为合适的拒绝
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);
如果调用displayError
,预期结果是什么?