-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
173 lines (141 loc) · 5.85 KB
/
index.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
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
// event listener for light and dark mode
document.addEventListener('DOMContentLoaded', () => {
const toggleMode = document.getElementById('toggleMode');
toggleMode.addEventListener('change', () => {
if (toggleMode.checked) {
container.classList.add('dark-mode');
} else {
container.classList.remove('dark-mode');
}
});
// Event listener for click in the search input
document.querySelector('.search-box input').addEventListener('click', (event) => {
search.click();
});
// Event listener for Enter key press in the search input
document.querySelector('.search-box input').addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
getWeatherForecast();
}
});
getWeatherByGeolocation();
});
const container = document.querySelector('.container');
const toggleModeBtn = document.getElementById('toggleMode');
const body = document.body;
const APIKey = 'config.myKey';
// Geolocation functions
function getWeatherByGeolocation() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
getWeatherByCoordinates(latitude, longitude);
}, (error) => {
console.error("Error getting geolocation:", error); //error message if location is not found
alert("Error getting your location. Please try again or enter your city manually.");
});
} else {
console.error("Geolocation is not supported by your browser");
alert("Geolocation is not supported by your browser. Please enter your city manually.");
}
}
function getWeatherForecast() {
const city = document.getElementById('city').value;
if (!city){
//error message if search box empty
alert('Please enter a city');
return;
}
//API openweathermap - current weather and hourly forecast
const currentWeatherUrl = `https://api.openweathermap.org/data/2.5/weather?units=metric&q=${city}&
units=metric&appid=${APIKey}`;
const forecastUrl = `https://api.openweathermap.org/data/2.5/forecast?units=metric&q=${city}&units
=metric&appid=${APIKey}`;
// Current Weather
fetch(currentWeatherUrl)
.then(response => response.json())
.then(data =>
{ displayWeather(data);
})
.catch(error => {
console.error('Error fetching current weather data:', error);
alert('Error fetching current weather data. Please try again.');
});
// Hourly weather
fetch(forecastUrl)
.then(response => response.json())
.then(data =>
{ displayHourlyForecast(data.list);
})
.catch(error => {
console.error('Error fetching current weather data:', error);
alert('Error fetching current weather data. Please try again.');
});
}
//display current weather
function displayWeather(data) {
const tempDivInfo = document.getElementById('temp-div');
const weatherInfoDiv = document.getElementById('weather-info');
const weatherIcon = document.getElementById('weather-icon');
const hourlyForecastDiv = document.getElementById('hourly-forecast');
//Clearing previous content after user input
weatherInfoDiv.innerHTML = "";
hourlyForecastDiv.innerHTML = "";
tempDivInfo.innerHTML = "";
if (data.cod === '404') {
weatherInfoDiv.innerHTML = `<p>${data.message}</p>` // checks response code if city found
} else {
const cityName = data.name.toUpperCase();
const temperature = parseInt(data.main.temp);
const description = data.weather[0].description;
const iconCode = data.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}@4x.png`;
const temperatureHTML = `<p>${temperature}°C</p>`;
const weatherHTML = `
<p>${description}</p>
<p><strong>${cityName}</strong></p>`;
tempDivInfo.innerHTML = temperatureHTML; //display temp
weatherInfoDiv.innerHTML = weatherHTML; //display city name
weatherIcon.src = iconUrl //display icons
weatherIcon.alt = description; //display weather description
showImage();
}
}
//display hourly forecast
function displayHourlyForecast(hourlyData) {
const hourlyForecastDiv = document.getElementById('hourly-forecast');
const next24Hours = hourlyData.slice(0, 24);
next24Hours.forEach(item => {
const dateTime = new Date(item.dt * 1000);
const hour = dateTime.getHours();
const temperature = parseInt(item.main.temp);
const iconCode = item.weather[0].icon;
const iconUrl = `https://openweathermap.org/img/wn/${iconCode}.png`
//creates a string = string for each hourlyItemHtml icon
const hourlyItemHtml = `
<div class = "hourly-item">
<span>${hour}:00</span>
<img src="${iconUrl}" alt="Hourly Weather Icon">
<span>${temperature}°C</span>
</div>`;
hourlyForecastDiv.innerHTML += hourlyItemHtml;
});
}
//displaying the weather icon
function showImage() {
const weatherIcon = document.getElementById('weather-icon');
weatherIcon.style.display = 'block';
}
function getWeatherByCoordinates(latitude, longitude) {
const weatherUrl = `https://api.openweathermap.org/data/2.5/weather?units=metric&lat=${latitude}&lon=${longitude}&appid=${APIKey}`;
fetch(weatherUrl)
.then(response => response.json())
.then(data => {
displayWeather(data);
})
.catch(error => {
console.error('Error fetching weather data:', error);
alert('Error fetching weather data. Please try again.');
});
}