【问题标题】:JavaScript issue with global variable assignment全局变量赋值的 JavaScript 问题
【发布时间】: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&deg;</strong>
</div>

【问题讨论】:

  • 为什么有你不使用的局部变量latitudelongitude?起初这让我很困惑。
  • 我想显示默认位置详细信息,即使有一些错误。因此,我决定用默认值声明全局变量,并且应该调用 fetchWeather 函数,而不考虑任何错误以显示默认值。

标签: javascript html api geolocation


【解决方案1】:

getCurrentPosition() 是异步的,但在使用结果之前您无需等待它完成。您应该从 success() 函数调用 fetchWeather(),因为它会在 getCurrentPosition() 完成时调用。

latitudelongitude 无需使用全局变量。将它们作为参数传递给fetchWeather()

setInterval(showWeather, 900000);
setTimeout(showWeather, 1000)

function showWeather() {
  var appid = "API_KEY_FOR_OPENWEATHERMAP";

  function success(position) {
    let latitude = position.coords.latitude;
    let longitude = position.coords.longitude;
    fetchWeather(latitude, longitude).then(response => {
      const icon = response.weather[0].icon;
      document.getElementById("city").innerHTML = response.name;
      document.getElementById("temp").innerHTML = response.main.temp + "&deg;";
      url = `https://openweathermap.org/img/w/${icon}.png`;
      document.getElementById("wicon").src = url;
    })
  }

  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(latitude, longitude) {
    var url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${appid}&units=metric`
    const response = await fetch(url);
    data = response.json();
    return data
  }
}
<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&deg;</strong>
</div>

【讨论】:

  • 嗨,我问的是好奇,“但你​​没有等待它完成之前使用结果”,但在这里他将其作为回调传递给权?
  • success 是回调,但fetchWeather 不是。
  • 有没有一种方法可以显示默认位置详细信息而不考虑任何错误或异常?
  • 您可以使用error() 函数中的默认位置调用fetchWeather()
  • 我将 fetchWeather() 函数包装在另一个函数中,然后使用外部函数进行调用,它使用默认的全局值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多