1+ // This example gets weather for any city based on user input.
2+ //
3+ // We'll use loadJSON() to get weather data from the API at
4+ // openweather.org.
5+ //
6+ // The results will not be available immediately. Just like when
7+ // you point your browser to a URL, it takes a moment to load. So
8+ // at the moment loadJSON is called, our 'result' will be empty.
9+ //
10+ // A callback is the name of a function that handles our data
11+ // when it is ready.
12+ //
13+ // We'll add a callback as the 2nd parameter to loadJSON, like this:
14+ //
15+ // loadJSON(url, callback)
16+
17+ var result ;
18+ var userInput ;
19+
20+ function setup ( ) {
21+ createCanvas ( 600 , 100 ) ;
22+ textSize ( 18 ) ;
23+ textAlign ( CENTER ) ;
24+ fill ( 0 ) ;
25+
26+ // Using p5dom addon (linked via index.html) to get user input.
27+ p = createP ( 'Enter City Name To Return Current Temperature' ) ;
28+ userInput = createInput ( 'New York' ) ;
29+ button = createButton ( 'submit' ) ;
30+
31+ button . mousePressed ( getWeather ) ; //getWeather() is the callback.
32+ }
33+
34+ function getWeather ( ) {
35+ background ( 255 ) ;
36+
37+ var cityName = userInput . value ( ) ;
38+ var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName + '&units=metric' ;
39+ result = loadJSON ( URL , displayWeather ) ; // displayWeather is the callback
40+
41+ print ( 'At the moment the mouse is clicked, the JSON object is empty: ' ) ;
42+ print ( result ) ; // result is not ready
43+ }
44+
45+ // Callback: loadJSON calls this function when finished loading.
46+ function displayWeather ( ) {
47+ print ( 'In the callback function, the JSON object is ready: ' )
48+ print ( result ) ; // result is ready!
49+
50+ var location = result . name ;
51+ var currentTemp = result . main . temp ;
52+ text ( 'Current temperature in ' + location + ' is ' + currentTemp + ' celsius' , width / 2 , height / 2 ) ;
53+ }
0 commit comments