-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
251 lines (215 loc) · 8.79 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
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
const weatherMain = document.getElementById("weatherMain");
const tempUnit = "°C";
const units = `metric`;
const apiKey = `3bfc1d6dd8d349f3ecab46491d371c9d`;
const locationCheck = document.getElementById("locationCheck");
let defaultImg= "https://images.unsplash.com/photo-1449157291145-7efd050a4d0e?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyNzkwODV8MHwxfHNlYXJjaHwxfHxUb3JvbnRvJTIwY2l0eXNjYXBlJTNFfGVufDB8MHx8fDE2NDcxMDc4NDk&ixlib=rb-1.2.1&q=80&w=1080";
document.body.style.backgroundImage = `url(${defaultImg})`;
document.body.style.height= "1200px";
const getIcon = (iconCode, appendable)=> {
let icon = new Image();
let iconSRC = `http://openweathermap.org/img/wn/${iconCode}@2x.png`;
icon.src= iconSRC;
icon.classList.add("weather-icon");
appendable.appendChild(icon);
};
const elMaker = (type, txt, id, parent) => {
let el = document.createElement(type);
el.innerText = txt;
el.id = id;
parent.appendChild(el);
};
const getBackground = async (city) => {
const randNum = Math.floor(Math.random()*10);
console.log(randNum);
const unsplashAPI = `https://api.unsplash.com/search/photos?page=${randNum}&query=${city} cityscape>&per_page=1000&orientation=landscape&client_id=YRV9QpR8OK8cKkF0QFk5yOMLv5DeSxQeVMPE1nijnBY`;
const photoFetch = await fetch(unsplashAPI, {mode:`cors`});
console.log(photoFetch.ok);
if (photoFetch.ok == false) {
const message = `An error has occured: ${response.status}`;
console.log(message);
}
else {
const photoData = await photoFetch.json();
let photo = photoData.results[randNum].urls.regular;
// console.log(photoData);
// console.log(photoData.results);
document.body.style.backgroundImage = "";
document.body.style.backgroundImage = `url(${photo})`;
}
setTimeout(()=> {
let imageAuthor = `${photoData.results[randNum].user.username}`;
console.log(imageAuthor);
let ownerDiv = document.createElement("div");
ownerDiv.id = "authorInfo";
ownerDiv.classList.add("weatherSquare");
let ownerLink = photoData.results[randNum].links.html;
ownerDiv.innerHTML = `Image of <strong>${city}</strong> randomly selected from unsplash.com. <br> Author: <strong>${imageAuthor}</strong>
<br><a href="${ownerLink}" target="_blank">${ownerLink}</a>`;
weatherMain.append(ownerDiv);
}, 1000);
};
const weatherKeyObj = [
{
title: "Temperature",
addon: `${tempUnit}`
},
{
title: "Feels Like",
addon: `${tempUnit}`
},
{
title: "Today's Low",
addon: `${tempUnit}`
},
{
title: "Today's High",
addon: `${tempUnit}`
},
{
title: "Pressure",
addon: "hPa"
},
{
title: "Humidity",
addon: "%"
},
{
title: "Sea Level Presure",
addon: "hPa"
},
{
title: "Ground Level Pressure",
addon: "hPa"
},
];
//async/await function.
const getWeather = async function(city) {
const apiLocation = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${units}&APPID=${apiKey}`;
// waits for server to grab data before passing into weatherDisplay.
const response = await fetch(apiLocation, {mode: 'cors'});
const weathData = await response.json();
// error handling
if (weathData.cod == "404" || weathData.cod == "400") {
weatherMain.innerHTML = "";
elMaker("h3","location not found", "error", weatherMain);
}
// return data
else if (weathData.cod == "200") {
// console.log(weathData);
weatherDisplay(weathData);
};
};
// adds eventlistener to form.
const cityField = document.getElementById("cityName");
const submitBtn = document.getElementById("submitBtn");
submitBtn.classList.add("btn-primary");
document.getElementById("submitBtn").addEventListener("click", () => {
event.preventDefault();
getWeather(cityField.value);
});
//display weather results on page
const weatherDisplay = (resp) => {
weatherMain.innerHTML = "";
// create city title using resp.name;
elMaker("h2",resp.name,"city", weatherMain);
elMaker("h5", "Current","current", weatherMain);
const gridContainer = document.createElement("div");
gridContainer.id = "grid-container";
weatherMain.appendChild(gridContainer);
document.getElementById("city").classList.add("weatherSquare");
// create grid items for temp, feels like, temp min, temp max, pressure.
for (let i = 0; i < Object.keys(resp.main).length; i++) {
let div = document.createElement("div");
let objKey = (Object.keys(resp.main)[i]);
div.id = objKey;
div.classList.add("weatherSquare");
div.innerHTML = `<h4>${weatherKeyObj[i].title}:</h2> ${Math.round(resp.main[objKey])}${weatherKeyObj[i].addon}`;
gridContainer.appendChild(div);
};
// create description
let description = document.createElement("div");
description.innerHTML = `<h4>Conditions:</h4>`;
description.id = "conditions";
let descText = document.createElement("p");
descText.innerText = `${resp.weather[0].description}`;
description.appendChild(descText);
description.classList.add("weatherSquare");
getIcon(resp.weather[0].icon, description);
gridContainer.appendChild(description);
// get coordinates
const lat = resp.coord.lat;
const lon = resp.coord.lon;
//HOURLY FORECAST
const genHourly = async function(lat, lon) {
const oneCallAPI = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=current,minutely,alerts,daily&units=${units}&appid=${apiKey}`;
const hourlyResp = await fetch(oneCallAPI, {mode:`cors`});
const hourlyRespData = await hourlyResp.json();
//hour heading
elMaker("h5","Hourly Forecast", "hourly",weatherMain);
//hourly container
const hourlyCont = document.createElement("div");
hourlyCont.id = "hourly-container";
weatherMain.appendChild(hourlyCont);
for (let j=0; j < 4; j++) { // makes 4 hours.
let hourDiv = document.createElement("div");
// converts unix timestamp to ms then into date
let dateConvert = new Date(hourlyRespData.hourly[j].dt*1000);
hourDiv.id= `hour-${j}`;
hourDiv.classList.add("weatherSquare");
// cuts off ms val
let timeOfDay = dateConvert.toLocaleTimeString().slice(-2);
dateConvert = dateConvert.toLocaleTimeString().slice(0,-6);
dateConvert = `${dateConvert} ${timeOfDay}`;
hourDiv.innerHTML = `<strong>${dateConvert}</strong>`;
hourlyCont.appendChild(hourDiv);
//add hourly weather to each section.
let hourlyData = hourlyRespData.hourly[j];
// console.log(hourlyData);
let hourlyWeather = document.createElement("div");
hourlyWeather.classList.add("hourly-data");
hourlyWeather.innerHTML =
`Temperature: ${Math.round(hourlyData.temp)}${tempUnit}<br>
Feels Like: ${Math.round(hourlyData["feels_like"])}${tempUnit}<br>
${hourlyData.weather[0].description}`;
hourDiv.appendChild(hourlyWeather);
// hourlyWeather.appendChild(icon);
getIcon(hourlyData.weather[0].icon, hourlyWeather);
};
};
genHourly(lat, lon);
//weekly weather
// use one call in above func.
const getWeekly = async (lat, lon) => {
let weeklyAPI = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=current,minutely,alerts,hourly&units=${units}&appid=${apiKey}`;
const weeklyResp = await fetch(weeklyAPI, {mode:`cors`});
const weeklyRespData = await weeklyResp.json();
// console.log(weeklyRespData);
//weekly container
const weeklyCont = document.createElement("div");
elMaker("h5", "Weekly Forecast", "weekly-title", weatherMain);
weeklyCont.id="weekly-container";
weatherMain.appendChild(weeklyCont);
// day divs
for (let k = 0; k < 6; k++) {
let dayDiv = document.createElement("div");
dayDiv.id =`day-${k+1}`;
dayDiv.classList.add("weatherSquare");
let dayData = weeklyRespData.daily[k];
let dateConvert = new Date(dayData.dt*1000);
let dateTrim = dateConvert.toDateString().slice(0,-4); // removes year
dayDiv.innerHTML = `<strong>${dateTrim}</strong>`;
weeklyCont.appendChild(dayDiv);
// day content
let dailyData = document.createElement("div");
dailyData.classList.add("daily-data");
dailyData.innerHTML = `${Math.round(dayData.temp.max)}${tempUnit} | ${Math.round(dayData.temp.min)}${tempUnit}<br>
${dayData.weather[0].description}`;
getIcon(dayData.weather[0].icon, dailyData);
dayDiv.appendChild(dailyData);
};
};
getWeekly(lat, lon);
getBackground(cityField.value);
cityField.value ="";
};