Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
86 lines (70 loc) · 2.96 KB
/
Copy pathscript.js
File metadata and controls
86 lines (70 loc) · 2.96 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const input = document.getElementById("input-name");
const btn = document.getElementById("submit-btn");
const cityName = document.getElementById("city-name");
const cityTime = document.getElementById("city-time");
const cityTemp = document.getElementById("city-temp");
const cityCondition = document.getElementById("city-condition");
const icon = document.getElementById("icon");
const loader = document.getElementById("loader");
btn.addEventListener('click', async () => {
if(input.value != '')
{
loader.style.display = 'block';
const data = await getCityData(input.value);
loader.style.display = 'none';
if (data.error) {
cityName.innerHTML = data.error.message;
cityTime.innerHTML = '';
cityTemp.innerHTML = '';
cityCondition.innerHTML = '';
icon.src = '';
}
else {
cityName.innerHTML = `${data.location.name}, ${data.location.region}, ${data.location.country}`;
const dt = new Date(data.location.localtime);
cityTime.innerHTML = `${dt.getHours()}:${dt.getMinutes()}`;
cityTemp.innerHTML = `${data.current.temp_c} °`;
cityCondition.innerHTML = data.current.condition.text;
icon.src = `https:${data.current.condition.icon}`;
}
}
else {
cityName.innerHTML = "Please Enter Name of the city above..."
}
})
async function getCityData(city) {
cityName.innerHTML = '';
cityTime.innerHTML = '';
cityTemp.innerHTML = '';
cityCondition.innerHTML = '';
icon.src = '';
const data = await fetch(`http://api.weatherapi.com/v1/current.json?key=572600794dac4b7c822153005230811&q=${city}&aqi=no`);
const dt = await data.json();
return dt;
}
window.addEventListener('load', (e)=> {
const successCallback = async (position) => {
loader.style.display = 'block';
const data = await getCityData(`${position.coords.latitude}, ${position.coords.longitude}`);
loader.style.display = 'none';
if (data.error) {
cityName.innerHTML = data.error.message;
cityTime.innerHTML = '';
cityTemp.innerHTML = '';
cityCondition.innerHTML = '';
icon.src = '';
}
else {
cityName.innerHTML = `${data.location.name}, ${data.location.region}, ${data.location.country}`;
const dt = new Date(data.location.localtime);
cityTime.innerHTML = `${dt.getHours()}:${dt.getMinutes()}`;
cityTemp.innerHTML = `${data.current.temp_c} °`;
cityCondition.innerHTML = data.current.condition.text;
icon.src = `https:${data.current.condition.icon}`;
}
};
const errorCallback = (error) => {
console.log(`Error is: ${error}`);
};
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
})