【发布时间】:2021-11-17 05:50:36
【问题描述】:
我正在尝试使用以下代码 sn-ps 创建一个天气小部件。但是,全局变量经度和纬度值不会在成功函数中更新。我已经尝试了 globalThis 和 window 对象的所有组合,但仍然无法解决问题。
setInterval(showWeather, 900000);
setTimeout(showWeather,1000)
function showWeather(){
var appid = "API_KEY_FOR_OPENWEATHERMAP";
var latitude = 0;
var longitude = 0;
function success(position){
window.latitude = position.coords.latitude;
window.longitude = position.coords.longitude;
}
function error(){
console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
}
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(success, error);
}else{
console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
}
async function fetchWeather(){
var url = `https://api.openweathermap.org/data/2.5/weather?lat=${window.latitude}&lon=${window.longitude}&appid=${appid}&units=metric`
const response = await fetch(url);
data = response.json();
return data
}
fetchWeather().then(response=>{
const icon = response.weather[0].icon;
document.getElementById("city").innerHTML = response.name;
document.getElementById("temp").innerHTML = response.main.temp + "°";
url = `https://openweathermap.org/img/w/${icon}.png`;
document.getElementById("wicon").src = url;
})
}
<h5 id="city">User Location</h5>
<div>
<img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
<strong id="temp">Temperature°</strong>
</div>
【问题讨论】:
-
为什么有你不使用的局部变量
latitude和longitude?起初这让我很困惑。 -
我想显示默认位置详细信息,即使有一些错误。因此,我决定用默认值声明全局变量,并且应该调用 fetchWeather 函数,而不考虑任何错误以显示默认值。
标签: javascript html api geolocation