-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
167 lines (136 loc) · 6.24 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const cityInput = document.querySelector(".city-input");
const searchButton = document.querySelector(".search-btn");
const locationButton = document.querySelector(".location-btn");
const currentWeatherDiv = document.querySelector(".current-weather");
const weatherCardsDiv = document.querySelector(".weather-cards");
const API_KEY = "bd92ad4dc8031e89c43cb5cb0edc8ada"; // API key for OpenWeatherMap API
function darkMode() {
let element = document.body;
let content = document.getElementById("DarkModetext");
element.className = "dark-mode";
content.innerText = "Dark Mode is ON";
let btn = document.getElementById("mybutton");
btn.addEventListener('click',() => {
btn.textContent = 'Light Mode';
document.getElementById("mybutton").value = "Light Mode";
document.getElementById("mybutton").style.backgroundColor='white';
});
}
function lightMode() {
let element = document.body;
let content = document.getElementById("DarkModetext");
element.className = "light-mode";
content.innerText = "Dark Mode is OFF";
}
function link()
{
getCityCoordinates();
var weatherData = document.getElementById("wd");
if(weatherData.style.display === "none") {
weatherData.style.display = "block";
}
else {
weatherData.style.display = "none";
}
}
const createWeatherCard = (cityName, weatherItem, index) => {
if(index === 0) { // HTML for the main weather card
return `<div class="details">
<h2>${cityName} (${weatherItem.dt_txt.split(" ")[0]})</h2>
<h6>Temperature: ${(weatherItem.main.temp - 273.15).toFixed(2)}°C</h6>
<h6>Wind: ${weatherItem.wind.speed} M/S</h6>
<h6>Humidity: ${weatherItem.main.humidity}%</h6>
</div>
<div class="icon">
<img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather-icon">
<h6>${weatherItem.weather[0].description}</h6>
</div>`;
} else { // HTML for the other five day forecast card
return `<li class="card">
<h3>(${weatherItem.dt_txt.split(" ")[0]})</h3>
<img src="https://openweathermap.org/img/wn/${weatherItem.weather[0].icon}@4x.png" alt="weather-icon">
<h6>Temp: ${(weatherItem.main.temp - 273.15).toFixed(2)}°C</h6>
<h6>Wind: ${weatherItem.wind.speed} M/S</h6>
<h6>Humidity: ${weatherItem.main.humidity}%</h6>
</li>`;
}
}
const getWeatherDetails = (cityName, latitude, longitude) => {
const WEATHER_API_URL = `https://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
fetch(WEATHER_API_URL).then(response => response.json()).then(data => {
// Filter the forecasts to get only one forecast per day
const uniqueForecastDays = [];
const fiveDaysForecast = data.list.filter(forecast => {
const forecastDate = new Date(forecast.dt_txt).getDate();
if (!uniqueForecastDays.includes(forecastDate)) {
return uniqueForecastDays.push(forecastDate);
}
});
console.log(fiveDaysForecast);
// Clearing previous weather data
cityInput.value = "";
currentWeatherDiv.innerHTML = "";
weatherCardsDiv.innerHTML = "";
// Creating weather cards and adding them to the DOM
fiveDaysForecast.forEach((weatherItem, index) => {
const html = createWeatherCard(cityName, weatherItem, index);
if (index === 0) {
currentWeatherDiv.insertAdjacentHTML("beforeend", html);
} else {
weatherCardsDiv.insertAdjacentHTML("beforeend", html);
}
});
}).catch(() => {
alert("An error occurred while fetching the weather forecast!");
});
}
const getCityCoordinates = () => {
const cityName = cityInput.value.trim();
console.log(cityName);
if (cityName === "") return;
const API_URL = `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${API_KEY}`;
// Get entered city coordinates (latitude, longitude, and name) from the API response
fetch(API_URL).then(response => response.json()).then(data => {
console.log(data);
if (!data.length) return alert(`No coordinates found for ${cityName}`);
const { lat, lon, name } = data[0];
getWeatherDetails(name, lat, lon);
}).catch(() => {
alert("An error occurred while fetching the coordinates!");
});
}
const getUserCoordinates = () => {
navigator.geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords; // Get coordinates of user location
console.log(latitude);
// Get city name from coordinates using reverse geocoding API
const API_URL = `https://api.openweathermap.org/geo/1.0/reverse?lat=${latitude}&lon=${longitude}&limit=1&appid=${API_KEY}`;
fetch(API_URL).then(response => response.json()).then(data => {
console.log(data);
const { name } = data[0];
console.log(name);
getWeatherDetails(name, latitude, longitude);
}).catch(() => {
alert("An error occurred while fetching the city name!");
});
},
error => { // Show alert if user denied the location permission
if (error.code === error.PERMISSION_DENIED) {
alert("Geolocation request denied. Please reset location permission to grant access again.");
} else {
alert("Geolocation request error. Please reset location permission.");
}
});
}
function locationlink()
{
getUserCoordinates();
var weatherData = document.getElementById("wd");
if(weatherData.style.display === "none") {
weatherData.style.display = "block";
}
else {
weatherData.style.display = "none";
}
}