Skip to content

Instantly share code, notes, and snippets.

@benfry
Last active July 6, 2023 01:01
Show Gist options
  • Save benfry/5785b65259be4fe5a5243ec9148027a2 to your computer and use it in GitHub Desktop.
Save benfry/5785b65259be4fe5a5243ec9148027a2 to your computer and use it in GitHub Desktop.

Getting Started

Start with the example sketch, and only make changes in the left-most tab.

For anything we do with the weather, your sketch will have this format:

// this will store all the weather data
let w;

function setup() {
  // your createCanvas() function here

  w = requestWeather(latitude, longitude);
}

function draw() {
  // set the background color or anything else

  // can't use “w” until it's “ready,” which means
  // the weather has loaded and is usable
  if (w.ready) {
    // do something using the data from “w”
  }
}

List of weather functions

A list of things you can ask of w.

Some functions can have a “range,” which is either days, hours, or minutes. When using one of these with a function, it will return an array of values.

Time

getTime()

Returns the time the forecast was taken. It uses the Moment class, which you can read about below.

getTimeDate()

For people already familiar with JavaScript, this returns the time (or a range) as a set of JavaScript Date objects. Read more about the Date object here.

Conditions

getConditionCode()

Return a code for the current weather that has no spaces. This can be used to map conditions to shapes or glyphs by name. Possible values include: Clear, Cloudy, Dust, Fog, Haze, MostlyClear, MostlyCloudy, PartlyCloudy, ScatteredThunderstorms, Smoke, Breezy, Windy, Drizzle, HeavyRain, Rain, Showers, Flurries, HeavySnow, MixedRainAndSleet, MixedRainAndSnow, MixedRainfall, MixedSnowAndSleet, ScatteredShowers, ScatteredSnowShowers, Sleet, Snow, SnowShowers, Blizzard, BlowingSnow, FreezingDrizzle, FreezingRain, Frigid, Hail, Hot, Hurricane, IsolatedThunderstorms, SevereThunderstorm, Thunderstorm, Tornado, or TropicalStorm.

Works for the current weather, and also with days or hours.

getConditionText()

A more human-readable version of the condition code, suitable for showing in an app. Includes spaces between words, and swaps And with an ampersand. For instance, MostlyCloudy is instead Mostly Cloudy, and MixedSnowAndSleet becomes Mixed Snow & Sleet.

Temperature

getTemperature() and getTemperature('hours')

getTemperature() returns the current temperature, and getTemperature('hours') returns the predicted temperatures for the next 243 hours (10 days and change).

For daily temperatures, use getTemperatureMin() and getTemperatureMax(), because there's no single temperature for a day. Only the low and high temperatures make sense.

getTemperatureMin('days') and getTemperatureMax('days')

Returns the min/max temperatures for the next 10 days in an array. Only works with days.

getApparentTemperature() and getApparentTemperature('hours')

What the temperature “feels like.” Use getApparentTemperature() for how the current temperature feels, or include 'hours' to get the prediction by hour. Does not work with days or minutes.

Precipitation

getPrecipitationChance()

Chance of precipitation as a number between 0 and 1, with 0 being 0%, 1 meaning 100%.

Only works with days, hours, or minutes. (There is no “current” chance, because it's either raining or not.)

getPrecipitationAmount('hours') and getPrecipitationAmount('days')

Prediction for how much precipitation will accumulate (in inches). Only works with hours and days.

getPrecipitationIntensity()

Current “intensity” of precipitation, measured in inches per hour. Also works with minutes, hours, or days.

getPrecipitationType('hours') and getPrecipitationType('days')

Type of precipitation that is predicted. Only works with hours and days.

Possible types are clear, rain, snow, sleet, hail, and mixed. Or just precipitation if the type of precipitation is unknown.

Wind

getWindSpeed()

Return the current wind speed in miles per hour.

Also works with hours, daytime, and overnight.

getWindDirection()

Wind direction in degrees (a number from 0 to 359).

Also works with hours, daytime, and overnight.

getWindGust('hours')

Wind gusts in miles per hour, only available for hourly values.

Other

getHumidity()

Returns current humidity percentage as a number between 0.0 and 1.0.

Also works with hours, daytime, and overnight.

getCloudCover()

Percentage of the sky covered by clouds (as a number between 0.0 and 1.0).

Also works with hours, daytime, and overnight.

getLatitude() and getLongitude()

Returns the actual lat/lon being used for the forecast.

This can also be helpful when using requestWeather('gps') to see the coordinates returned from the GPS on your device.

setUnits()

Because this course is based in the U.S., we're using Imperial units instead of metric. But you can change back to metric with setUnits(). For instance:

w.setUnits('metric');

Use that any time after requestWeather().

getData()

These functions wrap what's available in the API, but if you have experience working with JSON objects, you can access the information directly by using the getData() method.

For example:

w = requestWeather();
if (w.ready) {
  let weather = w.getData(); 
  // print the JSON object returned by the WeatherKit API to the console
  print(weather);  
}

The Moment class

Working with time when coding can be surprisingly difficult. The example code includes several functions to hide this complexity.

Getting the time of the forecast is done like so:

let when = w.getTime();

When you use the getTime() function, it returns a value that's represented as a Moment. There are lots of useful things you can do with a Moment, for instance:

  • when.hour() and when.minute() will provide the hour and minute of that point in time.
  • when.hourMinute() will give you a value like “9:16” for 9:16 am or pm.
  • when.hourMinuteLong() will return “9:16 pm” which includes the meridiem, a fancy way of referring to am or pm.
  • when.hour() is the hour, e.g. “9”
  • when.hour24() is in 24-hour format, e.g. “21”.
  • when.meridiem() returns just am or pm
  • when.hourShort() provides values like “6a” or “9p”
  • when.day() returns the day (1–31)
  • when.month() returns the month number (1–12)
  • when.monthName() will give you the (English) name of the month, e.g. “February”. If you just want the first letter of the month, add [0] to the end, as in when.monthName()[0].
  • when.year() is the four digit year, or you can use when.year() % 100 to get the two-digit year.
  • when.dayOfWeek() will give you the (English) name of the day of the week, e.g. “Thursday”. Or to get a single digit, use when.dayOfWeek()[0].
  • when.dayOfWeekIndex() is the index of the day, with 0 being Sunday, 3 being Wednesday, and 6 is Saturday. This is useful for use with the map() function.

The variable you use need not be called when, you could do this just the same:

let now = w.getTime();
print(now.hour());

…which would print the hour the forecast was taken to the console.

Examples

Start here:

  • SimpleTemperature – The most minimal example. Just gets the temperature and displays it on the screen.

A bit more advanced:

  • TemperatureBars – How to show more values retrieved from the API, in a simple app.

More specialized: note that these are more advanced than you might need, but cover topics that frequently come up early in the process.

  • CustomFonts – An example of using other fonts in your code. This will be explained in more detail during a future in-class Lab.

  • ImageRanges – As I was leaving for class one morning, my 8-year-old daughter handed me a sketch for her weather app idea. (I didn't realize she was paying attention to what I was doing.) It was to have the app show a flower at various stages depending on the temperature. This aligns with a frequent question that came up last week from people who wanted to swap between images based on criteria like temperature. This sketch uses her artwork for each of the four stages she set out, and is an example of the necessary logic to do the same type of thing in your own code.

  • WindDirection – This is an example of drawing things at an angle to show wind direction. This version uses sine and cosine to calculate the position.

  • WindDirectionRotate – Same as the WindDirection example, but uses the rotate() method to place the compass. May be trickier to understand, but more flexible.

How it Works

For the class, we're using a version of Apple's WeatherKit REST API, which you can read more about here.

The code in weather.js takes a latitude and longitude and passes it to weather.fathom.info, which handles calling the WeatherKit API. We're doing this because it's too complicated to sign everyone up for a developer account for the class.

Locations & Results

When you use the example code, you'll see the URL being used to retrieve the weather data in the console when you have the Developer Tools panel open in your browser. It will look something like:

Loading weather from https://weather.fathom.info/forecast/42.36031,-71.09414

If you open that link in a new tab, you can see all the data that's retrieved. (We recommend you use a JSON Formatter to make the information more readable).

Saving results

When viewing the results from a location like https://weather.fathom.info/forecast/42.36031,-71.09414 you can also save that for later use. Use File → Save in the browser and save the file as mit.json or whatever you like.

To use that forecast in your sketch, first drag and drop mit.json in the Processing window, which will add it to the data folder of your sketch. If it worked, you'll see a message that says 1 file added to sketch. in the console.

Next, change requestWeather(42.36031,-71.09414) to requestWeather('data/mit.json'), which will load that file instead of retrieving a new forecast. By saving several forecasts this way, you can easily test your app against multiple forecasts and locations.

Finding Locations

To find the lat/lon of another location:

  1. Search for it in Google Maps.
  2. Right-click the red “pin” marker for the location
  3. The lat/lon will be the first item in the pop-up menu
  4. Select the lat/lon, which will copy it to the clipboard
  5. Paste that location into your sketch

A list of locations

A collection of requestWeather() locations from the WeatherGirls project:

w = requestWeather(42.3604,-71.05797);  // boston
w = requestWeather(82.8628,135);  // antarctica
w = requestWeather(30.2672,-97.7431);  // austin
w = requestWeather(49.1951,16.6068);  // brno
w = requestWeather(-33.9249,18.4241);  // capetown
w = requestWeather(-22.970722,-43.1853);  // copacabana
w = requestWeather(32.794,32.794);  // haifa
w = requestWeather(54.2361,4.5481);  // isle of man
w = requestWeather(41.0082,28.9784);  // istanbul
w = requestWeather(-6.2,106.817);  // jakarta
w = requestWeather(31.6289,65.7372);  // kandahar
w = requestWeather(13.1631,-72.545);  // machu picchu
w = requestWeather(44.2706,-71.3033);  // mount washington
w = requestWeather(55.754093,37.620407);  // moscow
w = requestWeather(-1.2921,36.8219);  // nairobi
w = requestWeather(90,0);  // north pole
w = requestWeather(59.9139,10.7522);  // oslo
w = requestWeather(48.8566,2.3533);  // paris
w = requestWeather(59.9496,24.1052);  // riga
w = requestWeather(23.4126,25.6628);  // sahara desert
w = requestWeather(45.7503,-101.2004);  // standing rock
w = requestWeather(45.7503,99.1967);  // siberia
w = requestWeather(77.875,20.9752);  // svalbard
w = requestWeather(54,70);  // tierra del fuego
w = requestWeather(38.9072,-77.0369);  // washington, dc
w = requestWeather(-41.2865,174.7762);  // wellington
w = requestWeather(34.3416,108.9396);  // xi'an
w = requestWeather(32.6927,-114.6277);  // yuma
w = requestWeather(30.5765,31.5041);  // zagazig
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment