-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
82 lines (74 loc) · 2.93 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
let url = 'https://api.openweathermap.org/data/2.5/weather';
let APIkey = 'ea50fc4779b296f0c811b4543f95ed25';
let source = document.getElementById('hdlbrs_tmplt').innerHTML;
let template = Handlebars.compile(source);
document.getElementById('myFormID').addEventListener("submit", function(event){
event.preventDefault();
let cityName = event.target.cityName.value;
if (cityName === '') {
cityName = 'saint+petersburg';
} else {
cityName = cityName.replace(/ /g,"+");
console.log(cityName);
const result = {
city: '',
error: 'Congratulations, you broke the site! :) \n (Most likely, the problem is this: city not found )'
};
drawResult(result);
}
let output = document.getElementById('outputContainerID');
if (output) {
output.remove();
}
document.getElementById("loader").style.display = "block";
search(cityName).then((result) => {
drawResult(result);
});
});
const search = cityName => {
return new Promise(function(resolve,reject){
let destinationURL = url + '?q=' + cityName + '&APPID=' + APIkey;
let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
return resolve({ city : JSON.parse(xmlHttp.responseText), error: '' });
} else if (xmlHttp.readyState === 4 && xmlHttp.status !== 200) {
console.log(xmlHttp.responseText);
let data = JSON.parse(xmlHttp.responseText);
let errorString = 'Congratulations, you broke the site! :) \n (Most likely, the problem is this: ' + data.message + ' )';
return resolve({ city: '', error: errorString });
}
};
xmlHttp.open("GET", destinationURL, true);
xmlHttp.send(null);
})
};
const drawResult = ({city , error}) => {
document.getElementById("loader").style.display = "none";
let container;
if (city !== '') {
container = template({
place: city.name + ', ' + city.sys.country,
weather: 'Weather: ' + city.weather[0].main + ' ( ' + city.weather[0].description + ' )',
temp: 'Temperature: ' + (city.main.temp - 273.15).toFixed(0) + '°C',
wind: 'Wind: ' + city.wind.speed + ' m/s',
press: 'Pressure: ' + ((city.main.pressure * 100) / 133.322).toFixed(2) + ' Torr'
});
} else {
container = template({
errorString: error,
});
}
let body = document.getElementById('body');
let previous = document.getElementById('outputContainerID');
if (previous) {
previous.innerHTML = container
} else {
const div = document.createElement('div');
div.innerHTML = container;
div.id = 'outputContainerID';
body.appendChild(div);
}
};
exports.search = search;
exports.drawResult = drawResult;