-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
203 lines (171 loc) · 4.82 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
"use strict";
const form = document.querySelector("form#weatherForm");
const cities = [
"london", "prague", "berlin", "washington", "cairo", "moscow", "hong kong", "paris"
]
getWeather(cities[getRandom(cities.length)]); //initialize app with a random city
form.addEventListener("submit", e => {
e.preventDefault();
getWeather(getCity());
});
async function getWeather(city)
{
try {
showLoading();
errorPanel().clearError();
const cityCoord = await getCoord(city);
const cityData = await getCityData(cityCoord[0].lat, cityCoord[0].lon);
let img = await getImage(cityCoord[0].name); //Returns an empty hits array if query has no results
//look for a weather related image in case no results come back from prompt
if (img.hits.length === 0)
{
img = await getImage("Weather");
}
updateCity(cityCoord[0].name, cityCoord[0].country); //more accurate city name
updateDate(cityData.dt);
updateWeather(cityData);
const body = document.querySelector("body");
body.style.backgroundImage = `url(${img.hits[getRandom(img.hits.length)].largeImageURL})`;
}
catch (err)
{
errorPanel().showError(err)
}
}
function getCity()
{
const txtCity = document.querySelector("input#city");
const city = txtCity.value;
txtCity.value = "";
return city ;
}
function updateCity(cityName, Country)
{
const h2 = document.querySelector("h2");
h2.textContent = `${cityName}, ${Country}`;
}
function updateDate(dateUnix)
{
const h3 = document.querySelector("h3");
h3.textContent = new Date(dateUnix * 1000); //to convert from Unix time, it calculates in seconds while JS in milliseconds
}
function getRandom(upperBound)
{
return Math.floor(Math.random() * upperBound);
}
async function getCoord(cityName)
{
try
{
const response = await fetch(
`https://api.openweathermap.org/geo/1.0/direct?q=${cityName}
&appid=${getOpenWeatherKey()}`,
{
mode: "cors"
}
);
const data = await response.json();
if (data.length === 0) throw new Error("City Not Found");
return data;
}
catch(err)
{
return Promise.reject(err)
}
}
async function getCityData(lat, long)
{
try
{
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&units=${getMode()}&appid=${getOpenWeatherKey()}`,
{
mode: "cors"
}
);
const data = response.json();
hideLoading();
return data
}
catch(err)
{
return Promise.reject(err);
}
}
function getOpenWeatherKey()
{
//bad practice, but this is a free API key
return "0a7047fb9dfbdd373f66076c81a80a4e";
}
function getPixaBayKey()
{
return "15015852-74ad25fb66baa6531c44a804c";
}
async function getImage(query)
{
try
{
const pixaImg = await fetch(
`https://pixabay.com/api/?image_type=photo&orientation=horizontal&key=${getPixaBayKey()}&q=${query}`,
{
mode: "cors"
}
)
return pixaImg.json();
}
catch(err)
{
return Promise.reject(err);
}
}
function getMode()
{
return document.querySelector("select#mode").value.toLowerCase();
}
function errorPanel()
{
const panel = document.querySelector(".error-panel")
function showError(newError)
{
panel.textContent = newError;
}
function clearError()
{
panel.textContent = "";
}
return {showError, clearError}
}
function updateWeather(data)
{
const pInfoFields = document.querySelectorAll(".weather-info");
const isMetric = getMode() === "metric" ? true : false;
const units = {
temp: isMetric ? "° C" : "° F",
wind: isMetric ? "m/sec" : "Mph",
clouds: "%",
humidity: "%"
}
pInfoFields[0].textContent = `${data.clouds.all} ${units.clouds}`;
pInfoFields[1].textContent = `${data.main.temp} ${units.temp}`;
pInfoFields[2].textContent = `${data.wind.speed} ${units.wind}`;
pInfoFields[3].textContent = `${data.main.humidity} ${units.humidity}`;
}
function showLoading()
{
const elements = Array.from( document.querySelectorAll(".weather-info"));
elements.push(document.querySelector("h2"));
elements.push(document.querySelector("h3"));
elements.forEach(element => {
element.textContent = "Loading...";
element.classList.add("loading");
});
}
function hideLoading()
{
const elements = Array.from( document.querySelectorAll(".weather-info"));
elements.push(document.querySelector("h2"));
elements.push(document.querySelector("h3"));
elements.forEach(element => {
element.classList.remove("loading");
});
}