|
| 1 | +// Select DOM elements |
| 2 | +const searchBtn = document.querySelector(".search-btn"); |
| 3 | +const currentLocationBtn = document.querySelector(".current-location-btn"); |
| 4 | +const cityInput = document.querySelector(".city-input"); |
| 5 | +const weatherCards = document.querySelector(".weather-cards"); |
| 6 | +const todayWeatherCard = document.querySelector(".today-weather-card"); |
| 7 | + |
| 8 | +// Store API key |
| 9 | +const APIKEY = "c56c19f1c7c38425e05537cb48d74e41"; |
| 10 | + |
| 11 | +// Function to create a weather card |
| 12 | +const createWeatherCard = (cityName, weatherData, index) => { |
| 13 | + const tempCelsius = (weatherData.main.temp - 273.15).toFixed(2); |
| 14 | + const date = weatherData.dt_txt.split(" ")[0]; |
| 15 | + const iconURL = `https://openweathermap.org/img/wn/${weatherData.weather[0].icon}@4x.png`; |
| 16 | + const description = weatherData.weather[0].description; |
| 17 | + |
| 18 | + if (index === 0) { |
| 19 | + return `<div class="d-flex flex-column gap-2"> |
| 20 | + <p class="fs-3 fw-semibold"> |
| 21 | + ${cityName} (${date}) |
| 22 | + </p> |
| 23 | + <p>Temperature: ${tempCelsius}°C</p> |
| 24 | + <p>Wind: ${weatherData.wind.speed} M/S</p> |
| 25 | + <p>Humidity: ${weatherData.main.humidity}%</p> |
| 26 | + </div> |
| 27 | + <div class="text-center icon-box"> |
| 28 | + <img src="${iconURL}" alt="weather-conditions"/> |
| 29 | + <p>${description}</p> |
| 30 | + </div>`; |
| 31 | + } else { |
| 32 | + return `<div class="bg-secondary p-3 rounded-2 flex-grow-1 d-flex flex-column gap-1 weather-sub-card"> |
| 33 | + <p>(${date})</p> |
| 34 | + <img src="${iconURL.replace( |
| 35 | + "@4x", |
| 36 | + "@2x" |
| 37 | + )}" alt="weather-conditions"/> |
| 38 | + <p>Temp: ${tempCelsius}°C</p> |
| 39 | + <p>Wind: ${weatherData.wind.speed} M/S</p> |
| 40 | + <p">Humidity: ${weatherData.main.humidity}%</p> |
| 41 | + </div>`; |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +// General function to fetch weather data |
| 46 | +const fetchWeatherData = async (url) => { |
| 47 | + try { |
| 48 | + const response = await fetch(url); |
| 49 | + return await response.json(); |
| 50 | + } catch (error) { |
| 51 | + console.error(error); |
| 52 | + alert("An error occurred while fetching weather data."); |
| 53 | + } |
| 54 | +}; |
| 55 | + |
| 56 | +// Function to get weather information using city coordinates |
| 57 | +const getWeatherInfo = async (cityName, lat, lon) => { |
| 58 | + const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${APIKEY}`; |
| 59 | + const data = await fetchWeatherData(WEATHER_API_URL); |
| 60 | + |
| 61 | + if (data) { |
| 62 | + const uniqueDays = new Set(); |
| 63 | + const fiveDaysForecast = data.list.filter((forecast) => { |
| 64 | + const forecastDate = new Date(forecast.dt_txt).getDate(); |
| 65 | + if (!uniqueDays.has(forecastDate)) { |
| 66 | + uniqueDays.add(forecastDate); |
| 67 | + return true; |
| 68 | + } |
| 69 | + return false; |
| 70 | + }); |
| 71 | + |
| 72 | + cityInput.value = ""; |
| 73 | + todayWeatherCard.innerHTML = ""; |
| 74 | + weatherCards.innerHTML = ""; |
| 75 | + |
| 76 | + // Use a DocumentFragment to batch DOM updates |
| 77 | + const todayCard = createWeatherCard(cityName, fiveDaysForecast[0], 0); |
| 78 | + todayWeatherCard.insertAdjacentHTML("beforeend", todayCard); |
| 79 | + |
| 80 | + fiveDaysForecast.slice(1).forEach((weatherData, index) => { |
| 81 | + weatherCards.insertAdjacentHTML( |
| 82 | + "beforeend", |
| 83 | + createWeatherCard(cityName, weatherData, index + 1) |
| 84 | + ); |
| 85 | + }); |
| 86 | + } |
| 87 | +}; |
| 88 | + |
| 89 | +// Function to get city coordinates based on user input |
| 90 | +const getCityCoordinates = async () => { |
| 91 | + const cityName = cityInput.value.trim(); |
| 92 | + if (!cityName) return alert("Input can't be empty !"); |
| 93 | + |
| 94 | + const GEOCODING_API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&appid=${APIKEY}`; |
| 95 | + const data = await fetchWeatherData(GEOCODING_API_URL); |
| 96 | + |
| 97 | + if (data && data.length > 0) { |
| 98 | + const { name, lat, lon } = data[0]; |
| 99 | + getWeatherInfo(name, lat, lon); |
| 100 | + } else { |
| 101 | + alert(`No coordinates found for ${cityName}`); |
| 102 | + } |
| 103 | +}; |
| 104 | + |
| 105 | +// Function to get user coordinates and fetch weather data |
| 106 | +const getUserCoordinates = () => { |
| 107 | + navigator.geolocation.getCurrentPosition( |
| 108 | + async (position) => { |
| 109 | + const { latitude, longitude } = position.coords; |
| 110 | + const REVERSE_GEOCODING_URL = `https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=${APIKEY}`; |
| 111 | + const data = await fetchWeatherData(REVERSE_GEOCODING_URL); |
| 112 | + |
| 113 | + if (data && data.length > 0) { |
| 114 | + const { name } = data[0]; |
| 115 | + getWeatherInfo(name, latitude, longitude); |
| 116 | + } else { |
| 117 | + alert("Could not determine city from your location."); |
| 118 | + } |
| 119 | + }, |
| 120 | + (error) => { |
| 121 | + if (error.code === error.PERMISSION_DENIED) { |
| 122 | + alert("Permission denied to access location."); |
| 123 | + } |
| 124 | + } |
| 125 | + ); |
| 126 | +}; |
| 127 | + |
| 128 | +// Event listeners |
| 129 | +currentLocationBtn.addEventListener("click", getUserCoordinates); |
| 130 | +searchBtn.addEventListener("click", getCityCoordinates); |
| 131 | +cityInput.addEventListener( |
| 132 | + "keyup", |
| 133 | + (e) => e.key === "Enter" && getCityCoordinates() |
| 134 | +); |
0 commit comments