The power of the internet is the ability to share information. The web is a collection of documents that are linked together through hyperlinks. The web is also a collection of APIs (Application Programming Interfaces) that allow you to access and use data from other applications and services.
The purpose of this activity is to introduce an external weather source which can be used to serve up live weather information based on location and other parameters.
Prepare
This activity uses the third-party OpenWeatherMap API which will require you to obtain a free account in order to consume the data. You will only need to submit some basic information to obtain your free account. You do not need to use a credit card.
OpenWeatherMap
Navigate to OpenWeatherMap and find the "Search city" input box below the page's hero image.
Enter your city name in the input box provided and click Search.
Click on the appropriate search result for your city/location.
Review the weather data that is provided. You may want to switch to metric (C) or imperial (F) based results using the buttons in the upper-right corner of the search interface.
Under the Current & Forecast weather data collection, the free account includes:
the Current Weather Data collection
the 5 Day / 3 Hour Forecast collection
It is important that you understand that these are the collections that you can use with the Free Account. The others require a paid plan. There are always limitations regardless of the account, which is why it is important to reference the documentation on any API that you are using.
Current Weather Data API
Scroll down to the Current Weather Data API section, and click on the API doc button.
The Current Weather Data page explains how to call the current weather data for one location. Most APIs provide useful documentation to help you use the data. This page documents how to make an API call and shows example responses.
In the Current Weather Data API documentation, find the Call current weather data – How to make an API call section and study the API parameters and examples provided.
Scroll down to the Current weather and forecasts collection and find the Free account column. This account type will be sufficient.
This service is provided under Creative Commons Attribution-ShareAlike 4.0 International license (CC BY-SA 4.0). The data is open and licensed by the Open Data Commons Open Database License (ODbL).
Click on the Get API Key button under the Free column.
Proceed through the account sign up directions to get an API key which you will need to store and keep secure for your use only. This unique key is required in the data requests that you make to this service.
Do not use someone else's API key. Getting and using your own is part of the learning.
Any key in browser JavaScript is visible to everyone who views your page or repository. That is acceptable for this free practice key. Real projects keep keys on a server.
A new key can take a while to activate. If your first requests return a 401 error, wait and try again later.
Record this API key (appid) in a safe place. You will need it for this activity and for your assignments.
Activity Instructions
In this practice activity, you will create a simple page that displays some current weather conditions for a particular location in the world, Trier, Germany.
Location
Trier, Germany – Porta Nigra
Using Google Maps, find the latitude and longitude coordinates of Trier, Germany.
First locate the city on the map.
On the map, right-click on the city name.
Click on the latitude and longitude coordinates given. This will copy the coordinates to your clipboard.
You do not need that much precision. Round to two decimal places.
Location InformationCheck Your Coordinates
Trier, Germany is located at 49.75° N latitude and 6.64° E longitude.
HTML
In VS Code, create a new HTML page in your wdd231 folder.
Use the following template for the body of your HTML document:
<header>
<h1>OpenWeatherMap.org API Test</h1>
</header>
<main>
<p>The current temperature in Trier, Germany is <span id="current-temp"></span></p>
<figure>
<img id="weather-icon" src="" alt="">
<figcaption></figcaption>
</figure>
</main>
<footer>
[Enter Your Name Here] | OpenWeatherMap.org | CC BY-SA 4.0
</footer>
The empty src attribute on the image will be reported as an error by the HTML validator. This is temporary. Your JavaScript will fill in the src and alt values.
JavaScript
Create a new JavaScript file and reference it from your HTML with a <script> element. Make sure you place this file in an appropriate location given the course file and folder standards.
In the JavaScript file, first select all of the HTML elements that will need to be manipulated and assign them to const variables.
Check Your Understanding – Example
// select HTML elements in the document
const currentTemp = document.querySelector('#current-temp');
const weatherIcon = document.querySelector('#weather-icon');
const captionDesc = document.querySelector('figcaption');
Declare a const variable named "url" and assign it a valid URL string as given in the OpenWeatherMap API documentation that was presented above and bookmarked.
Start a query string with the "?" character as shown in the examples.
Use a & between each key/value pair in the query string in these next steps.
Specify the latitude and longitude of Trier, Germany using the information you have gathered and the examples provided.
Set the units to imperial: "units=imperial" or to metric: "units=metric"
Provide your API key: "appid=[enter your key here]"
Define an asynchronous function named "apiFetch()" that uses a try block to handle errors.
Store the results of the URL fetch into a variable named "response".
If the response is OK, then store the result of response.json() conversion in a variable named "data", and
Output the results to the console for testing.
Else, throw an Error using the response.text().
In the catch block, log the error to the console.
Remember to invoke the apiFetch() function with a call somewhere in your script. Check Your Understanding
async function apiFetch() {
try {
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
console.log(data); // testing only
// displayResults(data); // uncomment when ready
} else {
throw new Error(await response.text());
}
} catch (error) {
console.error(error);
}
}
apiFetch();
Run the page locally and view the console output. Find the current temperature (main.temp), the weather event description (weather[0].description), and image icon reference (weather[0].icon – 3 characters) in the data.
The weather array indicates that there can be more than one current weather event. You only need to focus on the first weather event if there is more than one.
The icon is just a preset code name that corresponds to OpenWeatherMap's library of images, which is found at the base address of https://openweathermap.org/img/wn/. Add the icon code, then @2x.png.
Example 10d@2x: Rain https://openweathermap.org/img/wn/10d@2x.png
All these images are .png file types. Here is a link to the documentation about Weather icons.
Build the displayResults function to output to the given HTML document.
Check Your Understanding – The blanks are intentional