/
Coderdev
/
web-static-labs
Обзор
Документация
Войти
/
Coderdev
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab6/task8/script.js
76 строк
3 KB
Coderdev
1
30 мар 2026, 18:31
30 мар 2026, 18:31
020a8dd
Код
Авторство
О чём код?
"use strict"; const API_KEY = "41e6cba5e43e166e06ca86f3a2b9f60c"; const CACHE_PREFIX = "lab6WeatherCache_"; const CACHE_TTL = 10 * 60 * 1000; const cityInput = document.getElementById("cityInput"); const getWeatherBtn = document.getElementById("getWeatherBtn"); const statusEl = document.getElementById("status"); const weatherCard = document.getElementById("weatherCard"); const cityTitle = document.getElementById("cityTitle"); const tempEl = document.getElementById("temp"); const descEl = document.getElementById("desc"); const windEl = document.getElementById("wind"); const sourceEl = document.getElementById("source"); getWeatherBtn.addEventListener("click", getWeather); async function getWeather() { const city = cityInput.value.trim(); if (!city) { statusEl.textContent = "Введите название города."; return; } const cacheKey = CACHE_PREFIX + city.toLowerCase(); const cached = localStorage.getItem(cacheKey); if (cached) { const parsed = JSON.parse(cached); if (Date.now() - parsed.savedAt < CACHE_TTL) { renderWeather(parsed.data, "localStorage"); statusEl.textContent = "Показаны данные из localStorage."; return; } } statusEl.textContent = "Загрузка погоды по API..."; try { const url = `https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${API_KEY}&units=metric&lang=ru`; const response = await fetch(url); if (!response.ok) { throw new Error("HTTP " + response.status); } const data = await response.json(); localStorage.setItem(cacheKey, JSON.stringify({ savedAt: Date.now(), data: data })); renderWeather(data, "API"); statusEl.textContent = "Показаны данные, полученные по API."; } catch (error) { statusEl.textContent = "Не удалось получить погоду."; weatherCard.hidden = true; } } function renderWeather(data, source) { weatherCard.hidden = false; cityTitle.textContent = data.name; tempEl.textContent = `${data.main.temp} °C`; descEl.textContent = data.weather[0].description; windEl.textContent = `${degToCompass(data.wind.deg)} (${data.wind.deg}°), ${data.wind.speed} м/с`; sourceEl.textContent = source; } function degToCompass(deg) { const directions = ["С", "СВ", "В", "ЮВ", "Ю", "ЮЗ", "З", "СЗ"]; return directions[Math.round(deg / 45) % 8]; }