-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
201 lines (180 loc) · 7.51 KB
/
index.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
// - - - - - - - - - - - -Tab Handling- - - - - - - - - - - -
const userTab = document.querySelector("[data-userWeather]");
const searchTab = document.querySelector("[data-searchWeather]");
const userContainer = document.querySelector(".weather-container");
const userInfoContainer = document.querySelector(".user-info-container");
const grantAccessContainer = document.querySelector( ".grant-location-container");
const searchForm = document.querySelector("[data-searchForm ]");
const searchInp = document.querySelector("[data-searchInp]");
const apiErrorContainer = document.querySelector(".api-error-container");
let currentTab = userTab;
const API_KEY = "d1845658f92b31c64bd94f06f7188c9c";
// tag ka initial color faded h jo current/old tab se css ki help se set hoga
currentTab.classList.add("current-tab");
function switchTab(clickedTab) {
apiErrorContainer.classList.remove("active");
if (clickedTab !== currentTab) {
currentTab.classList.remove("current-tab");
currentTab = clickedTab;
currentTab.classList.add("current-tab");
// if ke andar wali statement ka matlab search form visible ni tha, active ni tha matlab abhi use active karna
//h , visible karna h to newTab wahi h matlab
if (!searchForm.classList.contains("active")) {
userInfoContainer.classList.remove("active");
grantAccessContainer.classList.remove("active");
searchForm.classList.add("active");
} else {
//search wale par the pehle ab your weather pe aa gye click karke
searchForm.classList.remove("active");
userInfoContainer.classList.remove("active");
// ye default location ka weather dikhayega by checking ig location ka axxess h ki NodeIterator, ni h
// to askes to grant access
getFromSessionStorage();
}
// console.log("Current Tab", currentTab);
}
}
userTab.addEventListener("click", () => {
switchTab(userTab);
});
searchTab.addEventListener("click", () => {
switchTab(searchTab);
});
// - - - - - - - - - - - -User Weather Handling- - - - - - - - - - - -
const grantAccessBtn = document.querySelector("[data-grantAccess]");
const messageText = document.querySelector("[data-messageText]");
const loadingScreen = document.querySelector(".loading-container");
const apiErrorImg = document.querySelector("[data-notFoundImg]");
const apiErrorMessage = document.querySelector("[data-apiErrorText]");
const apiErrorBtn = document.querySelector("[data-apiErrorBtn]");
// Check if coordinates are already present in Session Storage
function getFromSessionStorage() {
const localCoordinates = sessionStorage.getItem("user-coordinates");
if (!localCoordinates) {
// agar local coordinates ni mile matlab acssess ni diya hua h location ka
grantAccessContainer.classList.add("active");
} else {
const coordinates = JSON.parse(localCoordinates);
fetchUserWeatherInfo(coordinates);
}
}
// Get Coordinates using geoLocation
// https://www.w3schools.com/html/html5_geolocation.asp
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
grantAccessBtn.style.display = "none";
messageText.innerText = "Geolocation is not supported by this browser.";
}
}
// Store User Coordinates
function showPosition(position) {
const userCoordinates = {
lat: position.coords.latitude,
lon: position.coords.longitude,
};
sessionStorage.setItem("user-coordinates", JSON.stringify(userCoordinates));
fetchUserWeatherInfo(userCoordinates);
}
// Handle any errors
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
messageText.innerText = "You denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
messageText.innerText = "Location information is unavailable.";
break;
case error.TIMEOUT:
messageText.innerText = "The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
messageText.innerText = "An unknown error occurred.";
break;
}
}
getFromSessionStorage();
grantAccessBtn.addEventListener("click", getLocation);
// fetch data from API - user weather info
async function fetchUserWeatherInfo(coordinates) {
const { lat, lon } = coordinates;
grantAccessContainer.classList.remove("active");
loadingScreen.classList.add("active");
try {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
);
const data = await res.json();
// console.log("User - Api Fetch Data", data);
if (!data.sys) {
throw data;
}
loadingScreen.classList.remove("active");
userInfoContainer.classList.add("active");
renderWeatherInfo(data);
} catch (error) {
// console.log("User - Api Fetch Error", error.message);
loadingScreen.classList.remove("active");
apiErrorContainer.classList.add("active");
apiErrorImg.style.display = "none";
apiErrorMessage.innerText = `Error: ${error?.message}`;
apiErrorBtn.addEventListener("click", fetchUserWeatherInfo);
}
}
// Render weather Info In UI
function renderWeatherInfo(weatherInfo) {
// console.log("Weather Info", weatherInfo);
const cityName = document.querySelector("[data-cityName]");
const countryIcon = document.querySelector("[data-countryIcon]");
const desc = 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 cloudiness = document.querySelector("[data-cloudiness]");
cityName.innerText = weatherInfo?.name;
countryIcon.src = `https://flagcdn.com/144x108/${weatherInfo?.sys?.country.toLowerCase()}.png`;
desc.innerText = weatherInfo?.weather?.[0]?.main;
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}%`;
cloudiness.innerText = `${weatherInfo?.clouds?.all}%`;
}
// - - - - - - - - - - - -Search Weather Handling- - - - - - - - - - - -
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
// agar kuch type kiye bina hi search kiya to return
if (searchInp.value === "") return;
// console.log(searchInp.value);
// otherwise search for that city
fetchSearchWeatherInfo(searchInp.value);
// and then set search to empty again for that timeonly kyokifir baad me search for city display hoga as usual
searchInp.value = "";
});
// fetch data from API - user weather info
async function fetchSearchWeatherInfo(city) {
loadingScreen.classList.add("active");
userInfoContainer.classList.remove("active");
apiErrorContainer.classList.remove("active");
try {
const res = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
);
const data = await res.json();
// console.log("Search - Api Fetch Data", data);
if (!data.sys) {
throw data;
}
loadingScreen.classList.remove("active");
userInfoContainer.classList.add("active");
renderWeatherInfo(data);
} catch (error) {
// console.log("Search - Api Fetch Error", error.message);
loadingScreen.classList.remove("active");
apiErrorContainer.classList.add("active");
apiErrorMessage.innerText = `${error?.message}`;
apiErrorBtn.style.display = "none";
}
}