-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
96 lines (65 loc) · 2.21 KB
/
script.js
File metadata and controls
96 lines (65 loc) · 2.21 KB
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
const apikey = "6626ff55c27e8c28ab1ecc35fd9a66a5";
const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");
const url = (city) =>
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apikey}`;
async function getWeatherByLocation(city) {
const resp = await fetch(url(city), { origin: "cors" });
const respData = await resp.json();
console.log(respData);
addWeatherToPage(respData);
}
function addWeatherToPage(data) {
const temp = KtoC(data.main.temp);
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
const ctx = document.getElementById('weather-chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Temperature (°C)', 'Humidity (%)'],
datasets: [{
label: 'Weather Info',
data: [temp, humidity],
backgroundColor: ['rgba(75, 192, 192, 0.2)', 'rgba(255, 99, 132, 0.2)'],
borderColor: ['rgba(75, 192, 192, 1)', 'rgba(255, 99, 132, 1)'],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
const weather = document.createElement("div");
weather.classList.add("weather");
weather.innerHTML = `
<h2><img src="https://openweathermap.org/img/wn/${
data.weather[0].icon
}@2x.png" /> ${temp}°C <img src="https://openweathermap.org/img/wn/${
data.weather[0].icon
}@2x.png" /></h2>
<small>${data.weather[0].main}</small>
<div class="more-info">
<p>Humidity : <span>${humidity}%</span></p>
<p>Wind speed : <span>${+Math.trunc(windSpeed * 3.16)}km/h</span></p>
</div>
`;
// cleanup
main.innerHTML = "";
main.appendChild(weather);
}
function KtoC(K) {
return Math.floor(K - 273.15);
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const city = search.value;
if (city) {
getWeatherByLocation(city);
}
});