-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
185 lines (157 loc) · 6.17 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
// API Key
const API_KEY = "168771779c71f3d64106d8a88376808a";
// Tab Switching
const userTab = document.querySelector("[data-userWeather]");
const searchTab = document.querySelector("[data-searchWeather]");
const searchForm = document.querySelector("[data-searchForm]");
const userInfoContainer = document.querySelector(".userInfoContainer");
const grantAccessContainer = document.querySelector(
".grantLocationContainer"
);
const loadingContainer = document.querySelector('.loadingContainer');
const notFound = document.querySelector('.errorContainer');
const errorBtn = document.querySelector('[data-errorButton]');
const errorText = document.querySelector('[data-errorText]');
const errorImage = document.querySelector('[data-errorImg]');
let currentTab = userTab;
currentTab.classList.add("currentTab");
getFromSessionStorage();
// console.log(userTab);
// console.log(searchTab);
function switchTab(newTab) {
notFound.classList.remove("active");
// check if newTab is already selected or not
if (currentTab != newTab) {
currentTab.classList.remove("currentTab");
currentTab = newTab;
currentTab.classList.add("currentTab");
// Check which TAb is Selected - search / your
// If Search Form not contains active class then add [Search Weather]
if (!searchForm.classList.contains("active")) {
searchForm.classList.add("active");
userInfoContainer.classList.remove("active");
grantAccessContainer.classList.remove("active");
}
// Your Weather
else {
searchForm.classList.remove("active");
userInfoContainer.classList.remove("active");
getFromSessionStorage();
}
}
}
userTab.addEventListener('click', () => {
switchTab(userTab);
});
searchTab.addEventListener('click', () => {
switchTab(searchTab);
});
function getFromSessionStorage() {
const localCoordinates = sessionStorage.getItem("userCoordinates");
// console.log(localCoordinates);
// Local Coordinates Not present - Grant Access Container
if (!localCoordinates) {
grantAccessContainer.classList.add('active');
}
else {
const coordinates = JSON.parse(localCoordinates);
fetchWeatherInfo(coordinates);
}
}
async function fetchWeatherInfo(coordinates) {
const { lat, lon } = coordinates;
// Remove Active Class from the Grant access Container
grantAccessContainer.classList.remove('active');
// loading
loadingContainer.classList.add('active');
// try - catch Block
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`);
const data = await response.json();
if (!data.sys) {
throw data;
}
loadingContainer.classList.remove('active');
userInfoContainer.classList.add('active');
renderWeatherInfo(data);
}
catch (err) {
loadingContainer.classList.remove('active');
notFound.classList.add('active');
errorImage.style.display = 'none';
errorText.innerText = `Error: ${err?.message}`;
errorBtn.style.display = 'block';
errorBtn.addEventListener("click", fetchWeatherInfo);
}
}
// Render Weather On UI
function renderWeatherInfo(weatherInfo) {
const cityName = document.querySelector('[data-cityName]');
const countryFlag = document.querySelector('[data-countryFlag]');
const description = document.querySelector('[data-weatherDesc]');
const weatherIcon = document.querySelector('[data-weatherIcon]');
const temp = document.querySelector('[data-temp]');
const windspeed = document.querySelector('[data-windspeed]');
const humidity = document.querySelector('[data-humidity]');
const clouds = document.querySelector('[data-clouds]');
cityName.innerText = weatherInfo?.name;
countryFlag.src = `https://flagcdn.com/144x108/${weatherInfo?.sys?.country.toLowerCase()}.png`;
description.innerText = weatherInfo?.weather?.[0]?.description;
weatherIcon.src = `http://openweathermap.org/img/w/${weatherInfo?.weather?.[0]?.icon}.png`;
temp.innerText = `${weatherInfo?.main?.temp.toFixed(2)} °C`;
windspeed.innerText = `${weatherInfo?.wind?.speed.toFixed(2)} m/s`;
humidity.innerText = `${weatherInfo?.main?.humidity.toFixed(2)} %`;
clouds.innerText = `${weatherInfo?.clouds?.all.toFixed(2)} %`;
}
const grantAccessButton = document.querySelector('[data-grantAccess]');
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
grantAccessButton.style.display = 'none';
}
}
function showPosition(position) {
const userCoordinates = {
lat: position.coords.latitude,
lon: position.coords.longitude
};
sessionStorage.setItem("userCoordinates", JSON.stringify(userCoordinates));
fetchWeatherInfo(userCoordinates);
}
grantAccessButton.addEventListener('click', getLocation);
// Search for weather
const searchInput = document.querySelector('[data-searchInput]');
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
if (searchInput.value === "") {
return;
}
// console.log(searchInput.value);
fetchSearchWeatherInfo(searchInput.value);
searchInput.value = "";
});
async function fetchSearchWeatherInfo(city) {
loadingContainer.classList.add("active");
userInfoContainer.classList.remove("active");
grantAccessContainer.classList.remove("active");
notFound.classList.remove("active");
try {
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`);
const data = await response.json();
if (!data.sys) {
throw data;
}
loadingContainer.classList.remove('active');
userInfoContainer.classList.add('active');
renderWeatherInfo(data);
}
catch (err) {
loadingContainer.classList.remove('active');
userInfoContainer.classList.remove('active');
notFound.classList.add('active');
errorText.innerText = `${err?.message}`;
errorBtn.style.display = "none";
}
}