-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgetWeather.js
More file actions
67 lines (53 loc) · 1.97 KB
/
getWeather.js
File metadata and controls
67 lines (53 loc) · 1.97 KB
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
// Converts unix time (milliseconds) to a local time UTC
function convertUnixToTime(unixTimestamp) {
dateObj = new Date(unixTimestamp);
utcString = dateObj.toUTCString();
return utcString;
}
// Gets the closest time to date based on a list of given times
// Both date and list have times in unix form (careful millisecond conversion)
function findClosestTime(date, list){
var count = Object.keys(list).length;
var index_closest = 0;
var closest = list[0].dt * 1000;
// console.log(closest);
for(var i = 1 ; i < count ; i++){
var isCloser = Math.abs(list[i].dt * 1000 - date) < Math.abs(closest - date);
closest = isCloser ? list[i].dt * 1000 : closest;
index_closest = isCloser ? i : index_closest;
}
// console.log(date);
// console.log(closest);
// console.log(convertUnixToTime(date));
// console.log(convertUnixToTime(closest));
// console.log(index_closest);
return index_closest;
}
function addWeatherItems(weather){
let output = [];
console.log(weather.weather[0].main);
if(weather.weather[0].main == "Clouds"){
output.push("umbrella");
}
console.log(output);
return output;
}
// Returns the weather for the given city and date/arrival time
function getWeather(city, date){
// OpenWeather 5-day, 3-hour weather forecast
var req = new XMLHttpRequest();
var url = "https://api.openweathermap.org/data/2.5/forecast?q=" + city + ",USA&appid=6d3ee0e6efe8a496f3440284ad37b6ab";
req.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var obj = JSON.parse(req.responseText);
var list = obj.list;
var weather_index = findClosestTime(date, list);
console.log(weather_index);
console.log("hi");
console.log(list[weather_index]);
return addWeatherItems(list[weather_index]);
}
}
req.open("GET", url, false);
req.send();
}