0% found this document useful (0 votes)
16 views10 pages

NODE3

The document provides a step-by-step guide to create a web application that fetches weather data from OpenWeatherMap using ES6 features like arrow functions, promises, and async/await, and displays the data in a graph using Chart.js. It includes instructions on obtaining an API key, setting up the HTML and JavaScript files, and implementing functions to fetch and process weather data. The application allows users to enter a city name and view the temperature forecast on a line chart.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views10 pages

NODE3

The document provides a step-by-step guide to create a web application that fetches weather data from OpenWeatherMap using ES6 features like arrow functions, promises, and async/await, and displays the data in a graph using Chart.js. It includes instructions on obtaining an API key, setting up the HTML and JavaScript files, and implementing functions to fetch and process weather data. The application allows users to enter a city name and view the temperature forecast on a line chart.

Uploaded by

amreen2825
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

NODE-3

3.Explore the features of ES6 like arrow functions, callbacks, promises,


async/await. Implement an application for reading the weather information from
openweathermap.org and display the information in the form of a graph on the
web page.

SOLUTION:
To get an API key from OpenWeatherMap, follow these steps:

1. Sign Up for OpenWeatherMap:

1. Go to the OpenWeatherMap website: https://openweathermap.org/.


2. Click on the Sign Up button in the upper-right corner of the homepage to create a new
account if you don’t already have one.
o If you already have an account, just click Login and sign in.
2. Log in or Create an Account:

 For New Users: Fill out the registration form with your details (name, email, and
password). After registering, you’ll receive a confirmation email to activate your
account.
 For Existing Users: If you already have an account, simply log in using your credentials.
3. Generate an API Key:

Once you are logged in:

1. Go to your Account page by clicking your username in the top-right corner and selecting
My Account from the dropdown menu.
2. In your account settings, navigate to the API Keys section. This is where you can create
and manage your API keys.
3. Click on the Create Key button to generate a new API key.
4. You will be asked to provide a name for your API key (e.g., "WeatherAppKey" or
something relevant), but this is optional.
5. After clicking Generate, your new API key will appear. It will be a long alphanumeric
string, something like this:
6. 123456789abcdef123456789abcdef12
Copy this API key — you’ll need it to make requests to the OpenWeatherMap API.
4. Using the API Key:

Now, you can use the generated API key in your requests to fetch weather data. In the
JavaScript code, replace 'YOUR_API_KEY' with the actual API key you generated:

const apiKey = 'YOUR_API_KEY'; // Replace this with the actual API key you copied

5. Check Usage Limits:

 OpenWeatherMap offers a free tier that allows up to 60 requests per minute, which is
sufficient for most small-scale applications.
 If you plan to make more frequent requests or need more advanced features, you can
check their pricing page for paid options.
6. Test the API:

To test if your API key works, you can use it in the URL for the OpenWeatherMap API. Here's
an example for getting the weather for London:

https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY

Replace YOUR_API_KEY with your actual API key. When you make a request to this URL, you
should receive weather data in JSON format.

Conclusion:

That's it! You now have an OpenWeatherMap API Key that you can use to fetch weather data
in your web application. Simply include your API key in the URL when making requests, and
you'll get the weather data for any city.

Sure! Let's go through the complete details for implementing a weather forecasting
application using ES6 features like arrow functions, callbacks, promises, async/await, and
displaying the data in a graph using Chart.js.
Project Overview:

We are going to create a web application that:

1. Fetches weather data from the OpenWeather Map API.


2. Displays the weather data (such as temperature) on a line chart using Chart.js.
3. Uses ES6 features like:
o Arrow functions
o Callbacks
o Promises
o Async/Await

Prerequisites:

1. API Key from OpenWeatherMap: You need an API key to access weather data. You can
obtain a free API key by signing up here: OpenWeatherMap.
2. Chart.js: A JavaScript library for rendering charts on a webpage.

Project Structure:

We’ll have two main files:

1. index.html: The HTML file to structure the page and include the user interface.
2. app.js: The JavaScript file to handle logic, data fetching, processing, and displaying the
graph.
1. HTML File (index.html):

This will include an input field for the user to enter a city, a button to fetch weather data, and
a <canvas> element to render the weather graph.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Weather Forecast</title>

<!-- Include Chart.js CDN -->

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>

body {

font-family: Arial, sans-serif;

text-align: center;

padding: 20px;

#cityInput {

padding: 10px;

font-size: 16px;

margin-bottom: 10px;

}
canvas {

max-width: 100%;

height: 400px;

</style>

</head>

<body>

<h1>Weather Forecast</h1>

<input type="text" id="cityInput" placeholder="Enter City Name" />

<button onclick="getWeatherData()">Get Weather</button>

<br />

<!-- The canvas will be used for the graph -->

<canvas id="weatherChart"></canvas>

<!-- Link to external JS -->

<script src="app.js"></script>

</body>

</html>
2. JavaScript File (app.js):

The JavaScript code will handle the fetching of weather data, processing the data, and
displaying it using Chart.js. It uses ES6 features like async/await, arrow functions, and
promises.

//2.1 Define API Key and Base URL:

// Define the API Key and base URL for the OpenWeatherMap API

const apiKey = 'YOUR_API_KEY'; // Get your free API key from


https://openweathermap.org/apiconst baseUrl =
'https://api.openweathermap.org/data/2.5/forecast';

//2.2 getWeatherData() Function (Async/Await):

//This function is triggered when the user clicks the "Get Weather" button. It uses async/await
//to fetch weather data from OpenWeatherMap.

const getWeatherData = async () => {

// Get the city name entered by the user

const city = document.getElementById('cityInput').value;

// Check if the city is not empty

if (!city) {

alert('Please enter a city name.');

return;

// Construct the URL to call the OpenWeatherMap API

const url = `${baseUrl}?q=${city}&units=metric&cnt=5&appid=${apiKey}`;

try {

// Make an asynchronous request to fetch weather data

const response = await fetch(url);


// If the response is not ok, throw an error

if (!response.ok) {

throw new Error('City not found');

// Parse the response JSON data

const data = await response.json();

// Process and extract relevant data from the response

const weatherData = processWeatherData(data);

// Display the weather data in a chart

displayWeatherGraph(weatherData);

} catch (error) {

// If there is an error, show an alert to the user

console.error('Error fetching weather data:', error);

alert('Error fetching weather data. Please try again.');

};

//2.3 processWeatherData() Function (Data Processing):

//This function processes the weather data from the API and extracts the times and
temperatures.

const processWeatherData = (data) => {

const times = []; // To store the times (hours)

const temperatures = []; // To store the temperatures in Celsius

// Iterate through the forecast data and extract the relevant details

data.list.forEach(item => {
const date = new Date(item.dt * 1000); // Convert timestamp to Date object

times.push(date.toLocaleTimeString()); // Format time

temperatures.push(item.main.temp); // Get the temperature in Celsius

});

return { times, temperatures };

};

2.4 displayWeatherGraph() Function (Chart.js):

This function uses Chart.js to display the weather data on a line chart.

const displayWeatherGraph = ({ times, temperatures }) => {

const ctx = document.getElementById('weatherChart').getContext('2d');

// Create a new line chart with the weather data

new Chart(ctx, {

type: 'line',

data: {

labels: times, // Times on the x-axis

datasets: [{

label: 'Temperature (°C)',

data: temperatures, // Temperatures on the y-axis

borderColor: 'rgba(75, 192, 192, 1)',

fill: false, // Do not fill under the curve

tension: 0.1

}]

},
options: {

scales: {

y: {

beginAtZero: false // Set y-axis to not start at zero

},

responsive: true

});

};

3. Explanation of ES6 Features:

Arrow Functions:

Arrow functions allow for a more concise function syntax. In the code above,
processWeatherData and displayWeatherGraph are written using arrow function syntax:

const processWeatherData = (data) =>{ ... }

Async/Await:

The getWeatherData function uses async/await for handling asynchronous operations:

 async marks a function that contains asynchronous code.


 await pauses the execution of the code until the promise is resolved, making
asynchronous code easier to read and write.
Example:

const response = await fetch(url); // Wait for the fetch to complete

const data = await response.json(); // Wait for the response to be parsed as JSON
Promises:

The fetch API returns a Promise, which we handle using await in getWeatherData. Promises
represent the eventual completion (or failure) of an asynchronous operation.

Template Literals:

We used template literals for easier string concatenation, such as when constructing the API
URL:

const url = `${baseUrl}?q=${city}&units=metric&cnt=5&appid=${apiKey}`;

4. Setting Up the Application:

4.1 Get OpenWeatherMap API Key:

1. Go to OpenWeatherMap.
2. Sign up for a free account and get your API key.
3. Replace 'YOUR_API_KEY' in the code with your actual API key.
4.2 Running the Application:

1. Save the HTML and JS files in the same directory.


2. Open index.html in your browser.
3. Enter the name of a city in the input field (e.g., "London") and click Get Weather.
4. The weather forecast for the next 5 hours will be displayed on the graph.

You might also like