Confused about a trivial error on Local Weather App [Solved]

Confused about a trivial error on Local Weather App [Solved]
0

#1

Hello, here is the app I’m working on, https://codepen.io/ngynkvn/pen/NAyPgN?editors=0010

I’ve been confused about an odd error that shows up in my console whenever I try to obtain my location. The app fails to display the requested data after clicking the “Get” button the first time, outputting the following error in console:

Uncaught TypeError: Cannot read property '0' of undefined

However, after clicking the “Get” button again, the requested information works and is displayed. I know the error is somehow linked to the fact that the API returns a portion of the weather information as an array, which is why I made use of var weather = json.weather[0]; on line 40. The reason I did this was because initially just trying to output json.weather[0].description would not work for me. The application still works, so this is not necessarily a problem, however I would like to know why this is happening. Thanks for reading.


#2

geolocation.getCurrentPosition() is an asynchronous operation. Inside the success callback, where you define lat and lon, make your $.getJSON() call there or call a function which makes that call.

navigator.geolocation.getCurrentPosition(function(position) {
  lon = position.coords.longitude;
  lat = position.coords.latitude;
  // here is where $.getJSON(weatherAPI, ...) should go
});

// code down here will run before the .getCurrentPosition success callback runs

#3

I see now, thank you for the quick reply!