forked from alex91-html/js-project-weather-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.ts
216 lines (168 loc) · 8.18 KB
/
script.ts
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
const API_KEY: string = "f70fe821b1e9718ced63c3a6bf1070e4";
document.addEventListener("DOMContentLoaded", () => {
const searchInput = document.getElementById("searchCity") as HTMLInputElement;
const searchButton = document.getElementById("searchButton") as HTMLButtonElement;
// Defining Weather Icons
const weatherIcons: { [key: string]: string } = {
"Clear": "./assets/Sun.svg",
"Clouds": "./assets/bad_weather.svg",
"Broken Clouds": "./assets/cloud.svg",
"Night": "./assets/night.svg",
}; //local asssets
// Defining Data Interfaces
interface WeatherData {
main: {
temp: number;
};
name: string;
weather: {
main: string;
description: string;
}[];
sys: {
sunrise: number;
sunset: number;
};
timezone: number;
}
// Interface for forecast data
interface ForecastEntry {
dt_txt: string;
main: {
temp_max: number;
temp_min: number;
};
weather: {
main: string;
}[];
}
interface ForecastData {
list: ForecastEntry[];
}
const updateWeatherUI = (weatherData: WeatherData, forecastData: 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: string = "Stockholm"): Promise<void> => { //all promise types through errors, typescript upset that function doesn't return anything
try {
console.log(`Fetching weather data for ${city}...`);
// Fetching Current and forecast Weather Data
const currentWeatherURL: string = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${API_KEY}`;
const forecastURL: string = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&units=metric&appid=${API_KEY}`;
const weatherResponse: Response = await fetch(currentWeatherURL);
if (!weatherResponse.ok) throw new Error(`Weather data not available (${weatherResponse.status})`);
const weatherData: WeatherData = await weatherResponse.json();
const forecastResponse: Response = await fetch(forecastURL);
if (!forecastResponse.ok) throw new Error(`Forecast data not available (${forecastResponse.status})`);
const forecastData: 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: ForecastData): void => {
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: { [date: string]: { high: number, low: number, icon: string } } = {};
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: string = searchInput.value.trim();
if (city) getWeather(city);
});
getWeather();
//functions for getting current coordinates and displaying according weather and forecast
const getWeatherByCoordinates = async (): Promise<void> => {
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: Response = await fetch(currentWeatherURL);
if (!weatherResponse.ok) throw new Error(`Weather data not available (${weatherResponse.status})`);
const weatherData: WeatherData = await weatherResponse.json();
const forecastResponse: Response = await fetch(forecastURL);
if (!forecastResponse.ok) throw new Error(`Forecast data not available (${forecastResponse.status})`);
const forecastData: 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") as HTMLButtonElement;
coordinatesButton.addEventListener("click", getWeatherByCoordinates);
});