-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (62 loc) · 2.43 KB
/
script.js
File metadata and controls
79 lines (62 loc) · 2.43 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
document.addEventListener("DOMContentLoaded", () => {
const cityInput = document.getElementById("city-input");
const getWeatherBtn = document.getElementById("get-weather-btn");
const weatherInfo = document.getElementById("weather-info");
const cityNameDisplay = document.getElementById("city-name");
const temperatureDisplay = document.getElementById("temperature");
const feelsLike = document.getElementById("feels-like");
const descriptionDisplay = document.getElementById("description");
const errorMsg = document.getElementById("error-msg");
const API_KEY = "Y37HT7W2XZJVA62MVSWT5585H"; //env variables
getWeatherBtn.addEventListener("click", async () => {
const city = cityInput.value.trim();
if (!city) {
return;
}
//it may throw you an error
//server/database is always in another continent
try {
const weatherData = await fetchWeatherData(city);
displayWeatherData(weatherData);
} catch (error) {
showError();
}
});
async function fetchWeatherData(city) {
//gets the data
const url = `https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/${city}?key=${API_KEY}`;
const response = await fetch(url);
console.log(typeof response);
console.log("RESPONSE: ", response);
if (!response.ok) {
throw new Error("City Not Found");
}
const data = await response.json();
return data;
}
function displayWeatherData(data) {
//display
console.log(data);
const { resolvedAddress, currentConditions } = data;
cityNameDisplay.textContent = resolvedAddress;
const tempInF = currentConditions.temp;
const tempInC = (tempInF - 32) * (5 / 9);
temperatureDisplay.textContent = `Temperature: ${Math.round(
tempInC
)}\u00B0C`;
const feelsLikeInF = currentConditions.feelslike;
const feelsLikeInC = (feelsLikeInF - 32) * (5 / 9);
feelsLike.textContent = `Feels like: ${Math.round(feelsLikeInC)}\u00B0C`;
descriptionDisplay.textContent = `Weather: ${currentConditions.conditions}`;
const iconName = currentConditions.icon;
const iconUrl = `/WeatherIcons/PNG/1st Set - Color/${iconName}.png`;
document.getElementById("weather-icon").src = iconUrl;
//unlock the display
weatherInfo.classList.remove("hidden");
errorMsg.classList.add("hidden");
}
function showError() {
weatherInfo.classList.add("hidden");
errorMsg.classList.remove("hidden");
}
});