We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'd like to pull weather information based on the user's location using the p5.geolocation library and Open Weather Map. I'm able to access latitude and longitude outside of preload, but when I attempt to do so within preload, they both show "undefined". What am I missing here?
var locationData;
function preload() {
locationData = getCurrentPosition();
var currentLat = locationData.latitude;
var currentLon = locationData.longitude;
var url = "//api.openweathermap.org/data/2.5/weather?lat=" + currentLat + "&lon=" + currentLon + "&appid=[myAPIkey]";
weather = loadJSON(url);
}
Answers
According to getCurrentPosition()'s reference below:
https://GitHub.com/bmoren/p5.geolocation#getcurrentposition-used-in-preload
The function is async, just like loadJSON(). That is, they take some time to get their resources.
However they don't block the execution! And if we try to access their resource too early, for example here:
var currentLat = locationData.latitude;
, much probably we're gonna getundefined
! :-SSRecently I've posted a similar solution to that conundrum at this forum thread below:
https://forum.Processing.org/two/discussion/18043/how-to-preload-images-using-filenames-from-a-txt-file
Worth checking out and adapt that solution to your case. :D
Seems like a good lead, but I'm having some difficulty adapting it to my situation (I'm still learning).
Would you mind elaborating?
@ https://forum.Processing.org/two/discussion/18043/how-to-preload-images-using-filenames-from-a-txt-file#Item_3, the sketch needs to grab the ".csv" file w/ loadTable() to get all the URLs before calling its many loadImage() functions.
In your case here, you need to fully grab getCurrentPosition() to form the URL before being able to run loadJSON().
The trick for both cases is to specify a callback for the 1st resource.
Then inside that callback, invoke the 2nd resource. *-:)