-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
219 lines (184 loc) · 8.1 KB
/
script.js
File metadata and controls
219 lines (184 loc) · 8.1 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
const container = document.querySelector('.container');
const search = document.querySelector('.search-box button');
const searchInput = document.querySelector('.search-box input');
const weatherBox = document.querySelector('.weather-box');
const weatherDetails = document.querySelector('.weather-details');
const error404 = document.querySelector('.not-found');
const cityHide = document.querySelector('.city-hide');
const APIKey = 'af0b4cc913b7702ba6ac740edb093db4';
let currentCity = ''; // Переменная для хранения текущего города
let isSearchCompleted = false; // Флаг для отслеживания завершения поиска
function getCityByLocation(lat, lon) {
return fetch(`https://api.openweathermap.org/geo/1.0/reverse?lat=${lat}&lon=${lon}&appid=${APIKey}`)
.then(response => response.json())
.then(data => {
if (data && data.length > 0) {
const city = data[0].name;
console.log(`City: ${city}`);
return city;
} else {
return '';
}
});
}
function translateCity(city, targetLanguage) {
return city;
}
function getWeatherFromAPI(city) {
if (city == '') return;
const API_WEATHER = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${APIKey}&lang=${currentLanguage}`;
return fetch(API_WEATHER)
.then(response => {
if (!response.ok) {
if (response.status === 404) {
return response.json();
}
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('Error fetching weather:', error);
throw error;
});
}
function getWeatherByCity(city) {
if (city == '') return;
getWeatherFromAPI(city)
.then(json => {
if (json.cod === '404') {
cityHide.textContent = city;
container.style.height = '400px';
weatherBox.classList.remove('active');
weatherDetails.classList.remove('active');
error404.classList.add('active');
searchInput.value = '';
searchInput.focus();
return;
}
isSearchCompleted = true; // Поиск завершён
// Остальная логика для отображения погоды
const image = document.querySelector('.weather-box img');
const temperature = document.querySelector('.weather-box .temperature');
const description = document.querySelector('.weather-box .description');
const humidity = document.querySelector('.weather-details .humidity span');
const wind = document.querySelector('.weather-details .wind span');
if (cityHide.textContent == city && prevLanguage == currentLanguage) {
return;
}
cityHide.textContent = city;
container.style.height = '555px';
container.classList.add('active');
weatherBox.classList.add('active');
weatherDetails.classList.add('active');
error404.classList.remove('active');
setTimeout(() => {
container.classList.remove('active');
}, 1600);
switch (json.weather[0].main) {
case 'Clear':
image.src = 'pics/clear.png';
break;
case 'Rain':
image.src = 'pics/rainy.png';
break;
case 'Snow':
image.src = 'pics/snowy.png';
break;
case 'Clouds':
image.src = 'pics/cloudy.png';
break;
case 'Mist':
image.src = 'pics/mist.png';
break;
case 'Haze':
image.src = 'pics/mist.png';
break;
case 'Thunderstorm':
image.src = 'pics/thunder.png';
break;
default:
image.src = 'pics/broken-clouds.png';
}
temperature.innerHTML = `${parseInt(json.main.temp)}<span>°C</span>`;
description.innerHTML = `${json.weather[0].description}`;
humidity.innerHTML = `${json.main.humidity}%`;
const windSpeed = parseInt(json.wind.speed);
wind.innerHTML = `${windSpeed}${translations[currentLanguage].windUnit}`;
const cloneContainers = ['.info-weather', '.info-humidity', '.info-wind'];
cloneContainers.forEach(selector => {
const original = document.querySelector(selector);
const clones = document.querySelectorAll(`${selector}.active-clone`);
clones.forEach(clone => clone.remove());
const newClone = original.cloneNode(true);
newClone.classList.add('active-clone');
newClone.id = `clone-${selector.replace('.', '')}`;
setTimeout(() => {
original.insertAdjacentElement('afterend', newClone);
}, 1600);
});
})
.catch(error => console.error('Error fetching weather data:', error));
}
document.getElementById('en').addEventListener('click', () => {
changeLanguage('en');
if (currentCity) {
const translatedCity = translateCity(currentCity, 'en'); // Переводим город на английский
searchInput.value = translatedCity; // Обновляем поле ввода
getWeatherByCity(translatedCity); // Обновляем данные
}
});
document.getElementById('ru').addEventListener('click', () => {
changeLanguage('ru');
if (currentCity) {
const translatedCity = translateCity(currentCity, 'ru'); // Переводим город на русский
searchInput.value = translatedCity; // Обновляем поле ввода
getWeatherByCity(translatedCity); // Обновляем данные
}
});
search.addEventListener('click', function () {
const city = document.querySelector('.search-box input').value;
currentCity = city; // Сохраняем текущий город
getWeatherByCity(city);
});
searchInput.addEventListener('keydown', function (event) {
const city = document.querySelector('.search-box input').value;
if (event.key === 'Enter') {
currentCity = city; // Сохраняем текущий город
getWeatherByCity(city);
}
});
searchInput.addEventListener('focus', function () {
if (isSearchCompleted) {
searchInput.value = ''; // Очищаем поле ввода
isSearchCompleted = false; // Сбрасываем флаг
}
});
document.addEventListener('DOMContentLoaded', function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
}
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
getCityByLocation(latitude, longitude)
.then(city => {
if (city) {
currentCity = city; // Сохраняем город
searchInput.value = city; // Обновляем поле ввода
getWeatherByCity(city); // Загружаем погоду
} else {
console.warn('No city found for your location. Please enter a city manually.');
alert('No city found for your location. Please enter a city manually.');
searchInput.value = ''; // Очищаем поле ввода
searchInput.focus(); // Устанавливаем фокус на поле ввода
}
})
.catch(error => {
console.error('Error:', error);
});
}
function error() {
return;
}
});