Experiment:4
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.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>Weather Information</h1>
<input type="text" id="cityInput" placeholder="Enter city name">
<button onclick="fetchWeatherData()">Get Weather</button>
<canvas id="weatherChart" width="400" height="200"></canvas>
<script src="app1.js"></script>
</body>
</html>
app1.js(Javascript file)
const apiKey = '1ab10da9b981b0867b516b1d5e191330'; // Replace with your
OpenWeatherMap API key
const apiUrl = (city) => `https://api.openweathermap.org/data/2.5/forecast?q=$
{city}&appid=${apiKey}&units=metric`;
const fetchWeatherData = () => {
const city = document.getElementById('cityInput').value;
if (!city) {
alert('Please enter a city name.');
return;
fetch(apiUrl(city))
.then(response => response.json())
.then(data => {
if (data.cod !== "200") {
alert('City not found.');
return;
// Process the data
const chartData = processWeatherData(data);
// Display the chart
displayChart(chartData);
})
.catch(error => console.error('Error fetching weather data:', error));
};
const processWeatherData = (data) => {
const labels = data.list.map(item => new Date(item.dt_txt).toLocaleTimeString());
const temps = data.list.map(item => item.main.temp);
return { labels, temps };
};
const displayChart = ({ labels, temps }) => {
const ctx = document.getElementById('weatherChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Temperature (°C)',
data: temps,
borderColor: 'rgba(75, 192, 192, 1)',
borderWidth: 1,
fill: false
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
};
Steps:
Create an OpenWeatherMap Account and Generate API Key
1. Visit the OpenWeatherMap website (https://openweathermap.org/) and click on "Sign Up"
or "Log In" to create an account or log into your existing account.
2. Once logged in, navigate to your account dashboard.
3. From the dashboard, locate my API Keys section and click on "Create Key" or "API Keys"
to generate a new API key.
4. Provide a name for your API key (e.g., "WeatherApp") and click on the "Generate" or
"Create" button.
5. Your API key will be generated and displayed on the screen. Make sure to copy it as we
will need it later.
Output: Initially the webpage looks like below
By entering the city then click on “Get weather “ then the following page will be displayed
If you enter invalid city name then , the city not message will be displayed
If you not enter any city name then,a message will be displayed for entering city name.