-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
303 lines (268 loc) · 11.4 KB
/
main.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
//this is an object
const config = {
countryurl: "https://api.countrystatecity.in/v1/countries",
//statesurl : https://api.countrystatecity.in/v1/countries/[ciso]/states
//cityeurl : https://api.countrystatecity.in/v1/countries/[ciso]/states/[siso]/cities
countrykey: "eGxJdkxCSWtBcUxjMkRBQVpXcFZrSDk1dWZ6ekpQQ1UxRVh3bXRFeA==",
weatherurl: "https://api.openweathermap.org/data/2.5/",
onecallurl: "https://api.openweathermap.org/data/2.5/onecall?lat={lat}&lon={lon}&exclude=minutely&appid={API key}",
weatherkey: "fd834ff020c870dba32a0a1d1ffbd4f6",
};
//getting location of user through GPS
document.addEventListener("DOMContentLoaded", async () => {
let lon;
let lat;
let units = "metric";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(async (position) => {
lon = position.coords.longitude;
lat = position.coords.latitude;
// console.log(lon,lat );
const apiEndPoint = `${config.weatherurl}weather?lat=${lat}&lon=${lon}&appid=${config.weatherkey}&units=${units}`;
const apiEndPoint1 = `${config.weatherurl}onecall?lat=${lat}&lon=${lon}&exclude=minutely&units=${units}&appid=${config.weatherkey}`;
const response = await fetch(apiEndPoint);
if (response.status != 200) {
throw new Error(`Something went wrong, status code : ${response.status}`);
}
const weather = await response.json();
const response1 = await fetch(apiEndPoint1);
if (response1.status != 200) {
throw new Error(`Something went wrong, status code : ${response1.status}`);
}
const weather1 = await response1.json();
// console.log(apiEndPoint1);
displayWeather(weather, weather1);
})
}
})
//fetching countries in select country //its an arrow function
const getCountries = async (areaName, ...args) => {
let apiEndPoint = config.countryurl;
switch (areaName) {
case `countries`:
apiEndPoint = config.countryurl;
break;
case `states`:
apiEndPoint = `${config.countryurl}/${args[0]}/states`;
break;
case `cities`:
apiEndPoint = `${config.countryurl}/${args[0]}/states/${args[1]}/cities`;
default:
}
const response = await fetch(apiEndPoint, {
headers: { "X-CSCAPI-KEY": config.countrykey },
});
if (response.status != 200) {
throw new Error(`Something went wrong, status code: ${response.status}`);
}
const countries = await response.json();
return countries;
};
//getting weather information
const getWeather = async (city, countryCode, units = "metric") => {
const apiEndPoint = `${config.weatherurl}weather?q=${city},${countryCode.toLowerCase()}&APPID=${config.weatherkey}&units=${units}`;
let lat;
let lon;
//console.log(apiEndPoint);
const response = await fetch(apiEndPoint);
if (response.status != 200) {
throw new Error(`Something went wrong, status code : ${response.status}`);
}
const weather = await response.json();
lat = weather.coord.lat;
lon = weather.coord.lon;
const apiEndPoint1 = `${config.weatherurl}onecall?lat=${lat}&lon=${lon}&exclude=minutely&units=${units}&appid=${config.weatherkey}`;
// console.log(apiEndPoint);
const response1 = await fetch(apiEndPoint1);
if (response1.status != 200) {
throw new Error(`Something went wrong, status code : ${response1.status}`);
}
const weather1 = await response1.json();
// console.log(weather1);
return [weather, weather1];
};
const getDate = (unixTimeStamp) => {
const milisec = unixTimeStamp * 1000;
const dateObj = new Date(milisec);
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const date = dateObj.toLocaleDateString('en-IN', options);
return date;
};
const getDay = (unixTimeStamp) => {
const milisec = unixTimeStamp * 1000;
const dateObj = new Date(milisec);
const options = {
weekday: "long",
// year: "numeric",
month: "numeric",
day: "numeric",
};
const date = dateObj.toLocaleDateString('en-IN', options);
return date;
};
const getTime = (unixTimeStamp) => {
const milisec = unixTimeStamp * 1000;
const dateObj = new Date(milisec);
const options = {
weekday: "long",
// year: "numeric",
// month: "numeric",
// day: "numeric",
hour: "numeric",
minute: "numeric",
};
const date = dateObj.toLocaleDateString('en-IN', options);
return date;
};
const getTime1 = (unixTimeStamp) => {
const milisec = unixTimeStamp * 1000;
const dateObj = new Date(milisec);
const options = {
//weekday: "long",
// year: "numeric",
// month: "numeric",
// day: "numeric",
hour: "numeric",
minute: "numeric",
};
const date = dateObj.toLocaleDateString('en-IN', options);
return date;
};
const displayWeather = (data, data1) => {
// console.log(data1)
const weatherWidget = `<div class="card alert text-center border-light">
<div class="card-body">
<h5 class="card-title fs-1 fst-italic text-center">
${data.name}, ${data.sys.country}
</h5>
<p class="fs-4">${getDate(data.dt)}</p>
<div class="tempcard">
<h6 class="card-subtitle cel mb-2">${data.main.temp}</h6>
<p class="card-text fs-4 mt-2">Minimum: ${data.main.temp_min}°C Maximum: ${data.main.temp_max}°C</p>
<p class="card-text fs-4 mt-2">Humidity: ${data.main.humidity}%</p>
</div>
${data.weather.map(w => `<div class="img-container">
<img src="https://openweathermap.org/img/wn/${w.icon}@2x.png" id="img"/>
</div>
<p class="fs-4">${w.description}</p>`).join("<br/>")}
</div>
</div>`;
let futureData = `
<div class="weather-forecast" id="weather-forecast">
<div class="weather-forecast-item">
<div class="other">
<div class="day">Today</div>
<img src="http://openweathermap.org/img/wn/${data1.daily[0].weather[0].icon}@2x.png" alt="" class="w-icon">
${data1.daily[0].weather[0].description}
<div class="temp">Day - ${data1.daily[0].temp.day}°C Sunrise - ${getTime1(data1.daily[0].sunrise).split(",")[1]}</div>
<div class="temp">Night - ${data1.daily[0].temp.night}°C Sunset - ${getTime1(data1.daily[0].sunset).split(",")[1]}</div>
<div class="humid">Humidity - ${data1.daily[0].humidity}%</div>
</div>
</div>
`
let newArr = data1.daily.slice(1);
futureData = futureData + `
<div class="weather-forecast" id="weather-forecast">
${newArr.map(obj => {
return `
<div class="weather-forecast-item">
<div class="other">
<div class="day">${getDay(obj.dt)}</div>
<img src=" http://openweathermap.org/img/wn/${obj.weather[0].icon}@2x.png" alt="" class="w-icon">
${data1.daily[0].weather[0].description}
<div class="temp">Day - ${obj.temp.day}°C Sunrise - ${getTime1(obj.sunrise).split(",")[1]}</div>
<div class="temp">Night - ${obj.temp.night}°C Sunset - ${getTime1(obj.sunset).split(",")[1]}</div>
<div class="humid">Humidity - ${obj.humidity}%</div>
</div>
</div>
`}).join(" ")
}
</div>
`;
let newArr1 = data1.hourly;
futureData1 = `
<div class="d-flex flex-row flex-nowrap overflow-auto" id="d1">
${newArr1.map(obj => {
return `
<div class="card card-body" id="cb">
<div class="card-header">${getTime(obj.dt)}</div>
<div class="content">
<img src=" http://openweathermap.org/img/wn/${obj.weather[0].icon}@2x.png" alt="" class="w-icon">
${obj.weather[0].description}
<p>${obj.feels_like} °C</p>
</div>
</div>
`}).join(" ")
}
</div>
`;
weatherdiv.innerHTML = weatherWidget;
fut24div.innerHTML = futureData1;
futurediv.innerHTML = futureData;
}
const countriesDropDownList = document.querySelector("#countrylist");
const statesDropDownList = document.querySelector("#statelist");
const citiesDropDownList = document.querySelector("#citylist");
const weatherdiv = document.querySelector("#weatherwidget");
const futurediv = document.querySelector("#future-forecast");
const fut24div = document.querySelector("#nxt24");
//calling above function
document.addEventListener("DOMContentLoaded", async () => {
const countries = await getCountries("countries");
//console.log(countries);
let countriesOption = "";
if (countries) {
countriesOption += `<option value="">Select country</option>`;
countries.forEach((country) => {
countriesOption += `<option value="${country.iso2}">${country.name}</option>`;
});
countriesDropDownList.innerHTML = countriesOption;
}
//list states
countriesDropDownList.addEventListener("change", async function () {
const selectedCountryCode = this.value;
//console.log("selected country code", selectedCountryCode);
const states = await getCountries("states", selectedCountryCode);
//console.log(states);
let statesOption = "";
if (states) {
statesOption += `<option value="">Select State</option>`;
states.forEach((state) => {
statesOption += `<option value="${state.iso2}">${state.name}</option>`;
});
statesDropDownList.innerHTML = statesOption;
statesDropDownList.disabled = false;
}
});
//list of cities
statesDropDownList.addEventListener("change", async function () {
const selectedCountryCode = countriesDropDownList.value;
const selectedStateCode = this.value;
//console.log("state code is", selectedStateCode);
const cities = await getCountries("cities", selectedCountryCode, selectedStateCode);
//console.log(cities);
let citiesOption = "";
if (cities) {
citiesOption += `<option value="">Select City</option>`;
cities.forEach((city) => {
citiesOption += `<option value="${city.name}">${city.name}</option>`;
});
citiesDropDownList.innerHTML = citiesOption;
citiesDropDownList.disabled = false;
}
});
//select the city to show weather
citiesDropDownList.addEventListener("change", async function () {
const selectedCity = this.value;
//console.log(selectedCity);
const selectedCountryCode = countriesDropDownList.value;
const [weatherInformation, weatherInformation1] = await getWeather(selectedCity, selectedCountryCode);
//console.log(weatherInformation);
displayWeather(weatherInformation, weatherInformation1);
})
});