-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (68 loc) · 2.62 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
let cityName = document.querySelector(".weather_city");
let dateTime = document.querySelector(".weather_date_time");
let w_forecast = document.querySelector(".weather_forecast");
let w_icon = document.querySelector(".weather_icon");
let w_temperature = document.querySelector(".weather_temperature");
let w_minTem = document.querySelector(".weather_min");
let w_maxTem = document.querySelector(".weather_max");
let w_feelsLike = document.querySelector(".weather_feelsLike");
let w_humidity = document.querySelector(".weather_humidity");
let w_wind = document.querySelector(".weather_wind");
let w_pressure = document.querySelector(".weather_pressure");
let citySearch = document.querySelector(".weather_search");
// To get the actual country name
const getCountryName = (code) => {
return new Intl.DisplayNames([code], {
type: "region",
}).of(code);
};
//To get date and time
const getDateTime = (dt) => {
const curDate = new Date(dt * 1000); // Convert seconds to milliseconds
console.log(curDate);
// const date = new Date();
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
};
const formatter = new Intl.DateTimeFormat("en-US", options);
// console.log(formatter);
return formatter.format(curDate);
};
let city = "rajkot";
// search functionalities
citySearch.addEventListener("submit", (e) => {
e.preventDefault();
let cityName = document.querySelector(".city_name");
console.log(cityName.value);
city = cityName.value;
getWeatherData();
cityName.value = "";
});
const getWeatherData = async () => {
const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=dd5ea011bc191c7edbc88df4813e2643`;
try {
const res = await fetch(weatherUrl);
const data = await res.json();
//console.log(data);
const { main, name, weather, wind, sys, dt } = data;
cityName.innerHTML = `${name}, ${getCountryName(sys.country)}`;
dateTime.innerHTML = getDateTime(dt);
w_forecast.innerHTML = weather[0].main;
w_icon.innerHTML = `<img src="http://openweathermap.org/img/wn/${weather[0].icon}@4x.png" />`;
w_temperature.innerHTML = `${main.temp}°`;
w_minTem.innerHTML = `${main.temp_min.toFixed()}°`;
w_maxTem.innerHTML = `Min: ${main.temp_max.toFixed()}°`;
w_feelsLike.innerHTML = `${main.feels_like.toFixed(2)}°`;
w_humidity.innerHTML = `${main.humidity}%`;
w_wind.innerHTML = `${wind.speed} m/s`;
w_pressure.innerHTML = `${main.pressure} hPa`;
} catch (error) {
console.log(error);
}
};
document.body.addEventListener("load", getWeatherData());