1

main is the JSON object's property that I want to get from the weather API, but I'm getting the following error:

Uncaught TypeError: Cannot read property 'main' of undefined

What's wrong?

HTML code:

<!-- display current temperature in Fahrenheight (default) -->
<div id="temp"></div>
<!-- display user's curent location -->
<div id="pos"></div>
<button id="loc">Show my location</button>
<button id="switch">Switch Metric Unit</button>

// return temperature and weather conditions for user's current location
var temp = document.getElementById('temp');
temp.innerHTML = "";
var tempStr = document.getElementById('temp').innerHTML;
var latitude;
var longitude;

JS code:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    latitude = position.coords.latitude;
    longitude = position.coords.longitude;
    // pos = position.coords.latitude + ", " + position.coords.longitude;
  })};

  $.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, 
    setTimeout(function(data) {
      $('#temp').html(celsiusToFahrenheit(data.main.temp) + "&deg;F");
    }), 1000)
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
Tiramisu
  • 35
  • 1
  • 9
  • The callback passed to `setTimeout` does not accept any arguments; `data` is undefined. `setTimeout` does not return any sort of value you can use as the second argument for `$.getJSON` either – Phil Sep 01 '17 at 04:30
  • 1
    In fact, why are you even attempting to use `setTimeout`? – Phil Sep 01 '17 at 04:31
  • Actually `$.getJSON` code need to be:- `$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude, function(data) { $('#temp').html(celsiusToFahrenheit(data.main.temp) + "°F"); });` also can you show us the content of `data` using `console.log(data);` – Alive to die - Anant Sep 01 '17 at 04:32
  • 1
    Also, because `latitude` and `longitude` are only assigned values within an asynchronous callback, they're not going to be available when you try to use them in `$.getJSON` – Phil Sep 01 '17 at 04:33
  • I actually meant to use setInterval() so that I can get the data continuously. But I defined latitude & longitude as global variables, so I don't understand why they wouldn't be accessible in $.getJSON? – Tiramisu Sep 01 '17 at 04:42
  • I understand now, the solution you referenced was helpful. Because they're assigned values within an asynchronous context, the rest of the code will be executed before, which means the variables will still be undefined. – Tiramisu Sep 01 '17 at 05:09

0 Answers0