forked from R0Y15/WeatherNow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
216 lines (194 loc) · 7.8 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
// JavaScript code for fetching and displaying the weather data
function getWeather() {
// Get the user input from the text box
var input = document.getElementById("input").value;
// Get the result div element
var result = document.getElementById("result");
var result_container = document.querySelector(".result-container");
// Hide the result initially
result.style.display = "none";
// Check if the input is not empty
if (input) {
// Create a URL for the weather API with the input as a query parameter
const token = "236bb39302420003220a7db6c237c584";
var url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
input +
"&units=metric&appid=" +
token;
// Fetch the data from the URL using the fetch API
fetch(url)
.then(function (response) {
// Check if the response is ok
if (response.ok) {
// Convert the response to JSON format
return response.json();
} else {
// Throw an error if the response is not ok
throw new Error("Something went wrong");
}
})
.then(function (data) {
// Extract the relevant data from the JSON object
var city = data.name; // The city name
var country = data.sys.country; // The country code
var temp = data.main.temp; // The current temperature in Celsius
var feels_like = data.main.feels_like; // The feels like temperature in Celsius
var humidity = data.main.humidity; // The humidity percentage
var wind = data.wind.speed; // The wind speed in meters per second
var description = data.weather[0].description; // The weather description
// Create a HTML string to display the data in a formatted way
html =
"<p><span class='value temp'>" +
temp +
" °C " +
getTemperatureIcon(description) +
"</span></p>";
html +=
"<p><span class='value description' style='text-transform:capitalize'>" +
description +
getWeatherIcon(description) +
"</span></p>";
html +=
"<p><span class='label'>Humidity:</span> <span class='value'>" +
humidity +
" % <i class='fas fa-tint fa-lg'></i></span></p>";
html +=
"<p><span class='label'>Wind:</span> <span class='value'>" +
wind +
" m/s <i class='fas fa-wind fa-lg'></i></span></p>";
// Set the inner HTML of the result div to the HTML string
result.innerHTML = html;
// Show the result div
result_container.style.display = "block";
result.style.display = "block";
})
.catch(function (error) {
// Handle any errors that may occur
alert(error.message);
});
} else {
// Alert the user if the input is empty
alert("Please enter a city name");
}
getGraph();
}
function getWeatherIcon(description) {
// Define mappings of weather descriptions to Font Awesome icons
var iconMappings = {
"clear sky": "<i class='fas fa-sun'></i>",
"few clouds": "<i class='fas fa-cloud-sun'></i>",
"scattered clouds": "<i class='fas fa-cloud'></i>",
"broken clouds": "<i class='fas fa-cloud'></i>",
"overcast clouds": "<i class='fas fa-cloud'></i>",
fog: "<i class='fas fa-smog'></i>",
"light rain": "<i class='fas fa-cloud-showers-heavy'></i>",
"moderate rain": "<i class='fas fa-cloud-showers-heavy'></i>",
"heavy rain": "<i class='fas fa-cloud-showers-heavy'></i>",
// Add more mappings as needed
};
// Check if the description exists in the mappings, and return the corresponding icon
if (iconMappings.hasOwnProperty(description.toLowerCase())) {
return iconMappings[description.toLowerCase()];
}
// If no matching description is found, return an empty string
return "";
}
function getTemperatureIcon(description) {
// Define mappings of weather descriptions to Font Awesome temperature icons
var iconMappings = {
"clear sky": "<i class='fas fa-sun'></i>",
"few clouds": "<i class='fas fa-sun'></i>",
"scattered clouds": "<i class='fas fa-cloud-sun'></i>",
"broken clouds": "<i class='fas fa-cloud-sun'></i>",
"overcast clouds": "<i class='fas fa-cloud'></i>",
fog: "<i class='fas fa-smog'></i>",
"light rain": "<i class='fas fa-cloud-showers-heavy'></i>",
"moderate rain": "<i class='fas fa-cloud-showers-heavy'></i>",
"heavy rain": "<i class='fas fa-cloud-showers-heavy'></i>",
// Add more mappings as needed
};
// Check if the description exists in the mappings, and return the corresponding icon
if (iconMappings.hasOwnProperty(description.toLowerCase())) {
return iconMappings[description.toLowerCase()];
}
// If no matching description is found, return an empty string
return "";
}
// Function for displaying graph for weather
async function getGraph(){
var cityInput = document.getElementById("input").value;
if (cityInput) {
const weatherData = await fetchWeatherData(cityInput);
if (weatherData) {
updateChart(weatherData);
}
} else {
alert('Please enter a city name or zip code.');
}
};
// Function to fetch data for the weather graph for a given city
async function fetchWeatherData(cityName) {
try {
// Replace 'YOUR_API_KEY' with your actual weather API key
const token = "236bb39302420003220a7db6c237c584";
var url =
"https://api.openweathermap.org/data/2.5/forecast?q=" +
cityName +
"&units=metric&appid=" +
token;
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching weather data:', error);
return null;
}
}
// Function to update the line graph with new data
function updateChart(data) {
// Extract relevant data from the API response (adjust according to your API)
const hourlyTemperature = data.list.map(item => item.main.temp);
const hourlyTime = data.list.map(item => new Date(item.dt * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// Update the chart data
hourlyChart.data.labels = hourlyTime;
hourlyChart.data.datasets[0].data = hourlyTemperature;
hourlyChart.update();
}
// Initial chart setup (you can set initial data or leave it empty)
const ctx = document.getElementById('hourlyChart').getContext('2d');
const hourlyChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [
{
label: 'Temperature (°C)',
data: [],
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.2)',
},
],
},
options: {
scales: {
x: {
title: {
display: true,
text: 'Hour'
}
},
y: {
title: {
display: true,
text: 'Temperature (°C)'
}
}
}
},
});
document.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
getWeather();
}
});