forked from alex91-html/js-project-weather-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
148 lines (148 loc) · 7.97 KB
/
script.js
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
"use strict";
const API_KEY = "f70fe821b1e9718ced63c3a6bf1070e4";
document.addEventListener("DOMContentLoaded", () => {
const searchInput = document.getElementById("searchCity");
const searchButton = document.getElementById("searchButton");
// Defining Weather Icons
const weatherIcons = {
"Clear": "./assets/Sun.svg",
"Clouds": "./assets/bad_weather.svg",
"Broken Clouds": "./assets/cloud.svg",
"Night": "./assets/night.svg",
}; //local asssets
const updateWeatherUI = (weatherData, forecastData) => {
document.getElementById("temperature").innerHTML = `${Math.round(weatherData.main.temp)}<span class="degree-symbol">°C</span>`;
document.getElementById("city").textContent = weatherData.name;
document.getElementById("weather-condition").textContent = weatherData.weather[0].description;
const weatherCondition = weatherData.weather[0].main;
let weatherImage = weatherIcons[weatherCondition] || "./assets/Sun.svg";
const localTime = Math.floor(Date.now() / 1000) + weatherData.timezone - new Date().getTimezoneOffset() * 60;
const isNight = localTime < weatherData.sys.sunrise || localTime > weatherData.sys.sunset;
const currentWeatherTwo = document.getElementById("currentWeatherTwo");
if (currentWeatherTwo) {
if (isNight) {
weatherImage = weatherIcons["Night"] || weatherImage;
currentWeatherTwo.classList.add("dark-weather");
}
else {
currentWeatherTwo.classList.remove("dark-weather");
}
}
const weatherImgElement = document.createElement("img");
weatherImgElement.src = weatherImage;
weatherImgElement.alt = weatherCondition;
weatherImgElement.className = "weather-icon";
const currentWeatherDiv = document.getElementById("current-weather");
currentWeatherDiv.innerHTML = "";
currentWeatherDiv.appendChild(weatherImgElement);
const timezoneOffset = weatherData.timezone;
document.getElementById("sunrise-time").textContent = new Date((weatherData.sys.sunrise + timezoneOffset) * 1000)
.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", hour12: false });
document.getElementById("sunset-time").textContent = new Date((weatherData.sys.sunset + timezoneOffset) * 1000)
.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", hour12: false });
updateForecast(forecastData);
};
// Fetching and Displaying Weather Data
const getWeather = async (city = "Stockholm") => {
try {
console.log(`Fetching weather data for ${city}...`);
// Fetching Current and forecast Weather Data
const currentWeatherURL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`;
const forecastURL = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&appid=${API_KEY}`;
const weatherResponse = await fetch(currentWeatherURL);
if (!weatherResponse.ok)
throw new Error(`Weather data not available (${weatherResponse.status})`);
const weatherData = await weatherResponse.json();
const forecastResponse = await fetch(forecastURL);
if (!forecastResponse.ok)
throw new Error(`Forecast data not available (${forecastResponse.status})`);
const forecastData = await forecastResponse.json();
updateWeatherUI(weatherData, forecastData);
}
catch (error) {
console.error("Error fetching weather:", error);
document.getElementById("city").textContent = "Unable to fetch weather!";
}
};
const updateForecast = (forecastData) => {
const forecastDays = document.getElementById("forecast-days");
const forecastIcons = document.getElementById("forecast-icons");
const forecastTemps = document.getElementById("forecast-temps");
forecastDays.innerHTML = "";
forecastIcons.innerHTML = "";
forecastTemps.innerHTML = "";
// Group forecast entries by date
const dailyForecast = {};
forecastData.list.forEach((entry) => {
const date = entry.dt_txt.split(" ")[0]; // Extract YYYY-MM-DD
if (!dailyForecast[date]) {
dailyForecast[date] = {
high: entry.main.temp_max,
low: entry.main.temp_min,
icon: entry.weather[0].main,
};
}
else {
dailyForecast[date].high = Math.max(dailyForecast[date].high, entry.main.temp_max);
dailyForecast[date].low = Math.min(dailyForecast[date].low, entry.main.temp_min);
}
});
// Display forecast for the next 7 days
Object.entries(dailyForecast).slice(0, 7).forEach(([date, data]) => {
const dayName = new Date(date).toLocaleDateString("en-GB", { weekday: "long" });
const dayElement = document.createElement("div");
dayElement.className = "day";
dayElement.textContent = dayName;
forecastDays.appendChild(dayElement);
const iconElement = document.createElement("img");
iconElement.className = "week-icon";
iconElement.src = weatherIcons[data.icon] || "./assets/Sun.svg"; // Default icon
forecastIcons.appendChild(iconElement);
const tempElement = document.createElement("div");
tempElement.className = "temp";
tempElement.textContent = `${Math.round(data.high)}°C / ${Math.round(data.low)}°C`;
forecastTemps.appendChild(tempElement);
});
console.log("Forecast updated successfully.");
};
searchButton.addEventListener("click", () => {
const city = searchInput.value.trim();
if (city)
getWeather(city);
});
getWeather();
//functions for getting current coordinates and displaying according weather and forecast
const getWeatherByCoordinates = async () => {
if (!navigator.geolocation) {
console.error("Geolocation is not supported by this browser.");
document.getElementById("city").textContent = "Geolocation not supported!";
return;
}
navigator.geolocation.getCurrentPosition(async (position) => {
try {
const { latitude, longitude } = position.coords;
console.log(`Fetching weather for coordinates: ${latitude}, ${longitude}...`);
const currentWeatherURL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${API_KEY}`;
const forecastURL = `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&units=metric&appid=${API_KEY}`;
const weatherResponse = await fetch(currentWeatherURL);
if (!weatherResponse.ok)
throw new Error(`Weather data not available (${weatherResponse.status})`);
const weatherData = await weatherResponse.json();
const forecastResponse = await fetch(forecastURL);
if (!forecastResponse.ok)
throw new Error(`Forecast data not available (${forecastResponse.status})`);
const forecastData = await forecastResponse.json();
updateWeatherUI(weatherData, forecastData);
}
catch (error) {
console.error("Error fetching weather:", error);
document.getElementById("city").textContent = "Unable to fetch weather!";
}
}, (error) => {
console.error("Error getting location:", error);
document.getElementById("city").textContent = "Location permission denied!";
});
};
const coordinatesButton = document.getElementById("coordinates");
coordinatesButton.addEventListener("click", getWeatherByCoordinates);
});