-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
252 lines (227 loc) · 10.8 KB
/
script.js
File metadata and controls
252 lines (227 loc) · 10.8 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
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
249
250
251
252
document.addEventListener('DOMContentLoaded', () => {
// Fungsi untuk menampilkan spinner
function showSpinner() {
const spinner = document.getElementById('loadingSpinner');
if (spinner) {
spinner.style.display = 'block'; // Tampilkan spinner
} else {
console.error('Spinner tidak ditemukan dalam showSpinner!');
}
}
// Fungsi untuk menyembunyikan spinner
function hideSpinner() {
const spinner = document.getElementById('loadingSpinner');
if (spinner) {
spinner.style.display = 'none'; // Sembunyikan spinner
} else {
console.error('Spinner tidak ditemukan dalam hideSpinner!');
}
}
// Fungsi untuk mengambil data cuaca berdasarkan kota
async function fetchWeatherData(city) {
showSpinner(); // Tampilkan spinner sebelum fetch
try {
const apiKey = '068e47eb2e272a1c00ca31e5c3bb5ec0'; // Pastikan API Key benar
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Proses data dan tampilkan hasil
const weatherIcon = `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
const tempCelsius = data.main.temp;
const tempFahrenheit = (tempCelsius * 9 / 5) + 32;
const weatherDescription = data.weather[0].description;
const cityName = data.name;
const countryCode = data.sys.country;
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
const weatherResult = document.getElementById('weatherResult');
if (weatherResult) {
weatherResult.innerHTML = `
<h2>${cityName}, ${countryCode}</h2>
<p>Temperature: ${tempFahrenheit.toFixed(1)}°F</p>
<p>Temperature: ${tempCelsius}°C</p>
<p>Weather: ${weatherDescription}</p>
<p>Humidity: ${humidity}%</p>
<p>Wind Speed: ${windSpeed} m/s</p>
<img src="${weatherIcon}" alt="weather icon">
`;
} else {
console.error('Elemen weatherResult tidak ditemukan!');
}
} catch (error) {
console.error('Fetch error:', error);
const weatherResult = document.getElementById('weatherResult');
if (weatherResult) {
weatherResult.innerHTML = `<p>Error: Unable to retrieve weather data</p>`;
}
} finally {
hideSpinner(); // Sembunyikan spinner setelah fetch
}
}
// Fungsi untuk mengambil data cuaca berdasarkan koordinat lokasi
async function fetchWeatherDataByLocation(latitude, longitude) {
showSpinner(); // Tampilkan spinner sebelum fetch
try {
const apiKey = '068e47eb2e272a1c00ca31e5c3bb5ec0'; // Pastikan API Key benar
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
displayWeatherData(data, 'geoWeatherResult');
} catch (error) {
console.error('Fetch error:', error);
const geoWeatherResult = document.getElementById('geoWeatherResult');
if (geoWeatherResult) {
geoWeatherResult.innerHTML = `<p>Error: Unable to retrieve weather data by location</p>`;
}
} finally {
hideSpinner(); // Sembunyikan spinner setelah fetch
}
}
// Fungsi untuk mengambil ramalan cuaca berdasarkan kota
async function fetchWeatherForecast(city) {
showSpinner(); // Tampilkan spinner sebelum fetch
try {
const apiKey = '068e47eb2e272a1c00ca31e5c3bb5ec0'; // Pastikan API Key benar
const response = await fetch(`https://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${apiKey}&units=metric`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
displayForecastData(data, 'forecastResult');
} catch (error) {
console.error('Fetch error:', error);
const forecastResult = document.getElementById('forecastResult');
if (forecastResult) {
forecastResult.innerHTML = `<p>Error: Unable to retrieve forecast data</p>`;
}
} finally {
hideSpinner(); // Sembunyikan spinner setelah fetch
}
}
// Fungsi untuk mengambil ramalan cuaca berdasarkan koordinat lokasi
async function fetchWeatherForecastByLocation(latitude, longitude) {
showSpinner(); // Tampilkan spinner sebelum fetch
try {
const apiKey = '068e47eb2e272a1c00ca31e5c3bb5ec0'; // Pastikan API Key benar
const response = await fetch(`https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
displayForecastData(data, 'geoForecastResult');
} catch (error) {
console.error('Fetch error:', error);
const geoForecastResult = document.getElementById('geoForecastResult');
if (geoForecastResult) {
geoForecastResult.innerHTML = `<p>Error: Unable to retrieve forecast data by location</p>`;
}
} finally {
hideSpinner(); // Sembunyikan spinner setelah fetch
}
}
// Fungsi untuk menampilkan ramalan cuaca
function displayForecastData(data, resultId) {
const forecastDiv = document.getElementById(resultId);
if (!forecastDiv) return;
const forecastList = data.list.filter((_, index) => index % 8 === 0).map(item => {
const date = new Date(item.dt * 1000);
const day = date.toLocaleDateString('en-US', { weekday: 'long' });
const weatherIcon = `https://openweathermap.org/img/wn/${item.weather[0].icon}@2x.png`;
const tempCelsius = item.main.temp;
const tempFahrenheit = (tempCelsius * 9 / 5) + 32;
const weatherDescription = item.weather[0].description;
return `
<div class="forecast-item">
<h3>${day}</h3>
<p>Temperature: ${tempFahrenheit.toFixed(1)}°F / ${tempCelsius}°C</p>
<p>Weather: ${weatherDescription}</p>
<img src="${weatherIcon}" alt="weather icon">
</div>
`;
}).join('');
forecastDiv.innerHTML = `
<h3>Weather Forecast:</h3>
${forecastList}
`;
}
// Fungsi untuk menampilkan data cuaca
function displayWeatherData(data, resultId) {
const weatherResult = document.getElementById(resultId);
if (!weatherResult) return;
const weatherIcon = `http://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
const tempCelsius = data.main.temp;
const tempFahrenheit = (tempCelsius * 9 / 5) + 32;
const weatherDescription = data.weather[0].description;
const cityName = data.name;
const countryCode = data.sys.country;
const humidity = data.main.humidity;
const windSpeed = data.wind.speed;
weatherResult.innerHTML = `
<h2>${cityName}, ${countryCode}</h2>
<p>Temperature: ${tempFahrenheit.toFixed(1)}°F</p>
<p>Temperature: ${tempCelsius}°C</p>
<p>Weather: ${weatherDescription}</p>
<p>Humidity: ${humidity}%</p>
<p>Wind Speed: ${windSpeed} m/s</p>
<img src="${weatherIcon}" alt="weather icon">
`;
}
// Fungsi untuk mendapatkan data cuaca berdasarkan lokasi pengguna
function getUserLocationWeather() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
fetchWeatherDataByLocation(latitude, longitude);
fetchWeatherForecastByLocation(latitude, longitude);
}, (error) => {
console.error('Geolocation error:', error);
const geoWeatherResult = document.getElementById('geoWeatherResult');
if (geoWeatherResult) {
geoWeatherResult.innerHTML = `<p>Error: Unable to retrieve location</p>`;
}
});
} else {
console.error('Geolocation is not supported by this browser.');
const geoWeatherResult = document.getElementById('geoWeatherResult');
if (geoWeatherResult) {
geoWeatherResult.innerHTML = `<p>Error: Geolocation is not supported by this browser.</p>`;
}
}
}
// Panggil fungsi getUserLocationWeather ketika halaman dimuat
getUserLocationWeather();
// Event listener untuk tombol Get Weather
const getWeatherBtn = document.getElementById('getWeatherBtn');
if (getWeatherBtn) {
getWeatherBtn.addEventListener('click', () => {
const cityInput = document.getElementById('cityInput').value;
if (cityInput) {
fetchWeatherData(cityInput);
fetchWeatherForecast(cityInput);
}
});
} else {
console.error('Tombol getWeatherBtn tidak ditemukan!');
}
// Menambahkan event listener untuk toggle theme switch
const themeToggle = document.getElementById('themeToggle');
if (themeToggle) {
themeToggle.addEventListener('change', function() {
const weatherApp = document.querySelector('.weather-app');
if (themeToggle.checked) {
weatherApp.classList.add('dark-mode');
weatherApp.classList.remove('light-mode');
} else {
weatherApp.classList.add('light-mode');
weatherApp.classList.remove('dark-mode');
}
});
} else {
console.error('Tombol themeToggle tidak ditemukan!');
}
});