【发布时间】:2016-08-27 23:55:11
【问题描述】:
如何更正下面的代码,使其不返回 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);
【问题讨论】:
-
如果
displayError被调用,预期的结果是什么?
标签: javascript jquery ajax api geolocation