Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
Problema de JavaScript con la asignación de variables globales

Estoy tratando de crear un widget meteorológico usando los fragmentos de código a continuación. Sin embargo, los valores de longitud y latitud de las variables globales no se actualizan en la función de éxito. Probé todas las combinaciones de objetos globalThis y window, pero aún no he podido resolver el problema.

 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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

getCurrentPosition() es asíncrono, pero no está esperando a que termine antes de usar los resultados. Debe llamar a fetchWeather() desde la función success() , ya que se llama cuando getCurrentPosition() .

No es necesario utilizar variables globales para la latitude y longitude . Páselos como argumentos a 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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!