From 5007ab8a78dd290531c16cd29d1ad238148b8684 Mon Sep 17 00:00:00 2001 From: "Your Name alexandrameija@hotmail.com" Date: Wed, 13 Sep 2023 20:40:27 +0200 Subject: [PATCH] -m added geolocation --- script.js | 270 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 141 insertions(+), 129 deletions(-) diff --git a/script.js b/script.js index 1e600a675..647e4915d 100644 --- a/script.js +++ b/script.js @@ -3,138 +3,150 @@ const day = document.getElementById("day"); const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; const container = document.getElementById('sthweather'); const messageContainer = document.getElementById('message-text'); +const apiKey = '8fa7c461aec946fde31f330992fce9d6'; -fetch('https://api.openweathermap.org/data/2.5/weather?q=Stockholm,Sweden&units=metric&APPID=8fa7c461aec946fde31f330992fce9d6') - .then((response) => { - return response.json(); - }) - .then((json) => { - const cityName = json.name; - const temperature = json.main.temp; - const weatherDescription = json.weather[0].description; - const sunsetTimestamp = json.sys.sunset * 1000; - const sunriseTimestamp = json.sys.sunrise * 1000; - const feelsLike = json.main.feels_like; - - // Create Date objects for sunset and sunrise times - const sunset = new Date(sunsetTimestamp); - const sunrise = new Date(sunriseTimestamp); - const currentDayOfWeek = new Date().getDay(); - - - function generateWeatherMessage(description) { - let message = ""; - - if (description.includes("rain")) { - message = "Don't forget your umbrella!"; - } else if (description.includes("cloud")) { - message = "Here's hoping for a sunny sky later on"; - } else if (description.includes("sun")) { - message = "Keep them sunglasses nearby"; - } else { - message = "Weather conditions may vary."; +function fetchWeatherDataByCoordinates(latitude, longitude) { + const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&units=metric&appid=${apiKey}`; + + fetch(apiUrl) + .then((response) => { + if (!response.ok) { + throw new Error('Network response was not ok'); } - - return message; - } - - // Generate the weather message based on the weather description - const message = generateWeatherMessage(weatherDescription); - - // Display the weather message - messageContainer.innerHTML = `

${message}

`; - - - - container.innerHTML = ` -

Here's the weather in ${cityName}

-

${weekdays[currentDayOfWeek]}

-

Temperature: ${temperature}°C

-

Temperature: ${temperature}°C

-

Weather: ${weatherDescription}

-

Sunrise: ${sunrise.toLocaleTimeString()}

-

Sunset: ${sunset.toLocaleTimeString()}

-

Weather feels like: ${feelsLike}°C

- `; - }) - .catch((error) => { - console.error('Error fetching weather data:', error); - }); - - //display message depending on kind of weather for example if rain "Don't forget your umbrella", cloudy "You might wanna bring an extra sweater and so on" - - function fetchWeatherData() { - fetch('https://api.openweathermap.org/data/2.5/forecast?q=Stockholm,Sweden&units=metric&APPID=8fa7c461aec946fde31f330992fce9d6') - .then((response) => { - if (!response.ok) { - throw new Error('Network response was not ok'); + return response.json(); + }) + .then((json) => { + const cityName = json.name; + const temperature = json.main.temp; + const weatherDescription = json.weather[0].description; + const sunsetTimestamp = json.sys.sunset * 1000; + const sunriseTimestamp = json.sys.sunrise * 1000; + const feelsLike = json.main.feels_like; + + // Create Date objects for sunset and sunrise times + const sunset = new Date(sunsetTimestamp); + const sunrise = new Date(sunriseTimestamp); + const currentDayOfWeek = new Date().getDay(); + + function generateWeatherMessage(description) { + let message = ""; + + if (description.includes("rain")) { + message = "Don't forget your umbrella!"; + } else if (description.includes("cloud")) { + message = "Here's hoping for a sunny sky later on"; + } else if (description.includes("clear sky")) { + message = "Keep them sunglasses nearby"; + } else { + message = "Weather conditions may vary."; } - return response.json(); - }) - .then((json) => { - - // Filter and group forecast data by date - const groupedForecast = json.list.reduce((result, item) => { - const date = item.dt_txt.split(' ')[0]; - if (!result[date]) { - result[date] = []; - } - result[date].push(item); - return result; - }, {}); - - // Calculate and display morning (9 AM) and evening (9 PM) temperatures for each day - for (const date in groupedForecast) { - if (groupedForecast.hasOwnProperty(date)) { - const forecastItems = groupedForecast[date]; - const morningItem = forecastItems.find((item) => item.dt_txt.includes("09:00")); - const eveningItem = forecastItems.find((item) => item.dt_txt.includes("21:00")); - - if (morningItem && eveningItem) { - const morningTemperature = morningItem.main.temp; // Temperature at 9:00 AM - const eveningTemperature = eveningItem.main.temp; // Temperature at 9:00 PM - const morningFeelsLike = morningItem.main.feels_like; // "Feels like" temperature at 9:00 AM - const eveningFeelsLike = eveningItem.main.feels_like; // "Feels like" temperature at 9:00 PM - const morningDescription = morningItem.weather[0].description; // Weather description at 9:00 AM - const eveningDescription = eveningItem.weather[0].description; // Weather description at 9:00 PM - const morningHumidity = morningItem.main.humidity; // Humidity at 9:00 AM - const eveningHumidity = eveningItem.main.humidity; // Humidity at 9:00 PM - - - // Get the day of the week for the date - const weekday = new Date(date).getDay(); - - // Display the forecast for the day with time of day and "feels like" temperature - day.innerHTML += ` -
-

${weekdays[weekday]}

-

At 9 am

-

Temperature: ${morningTemperature}°C (Feels like: ${morningFeelsLike}°C)

-

Weather: ${morningDescription}

-

Humidity: ${morningHumidity}%

-

At 9 pm

-

Temperature: ${eveningTemperature}°C (Feels like: ${eveningFeelsLike}°C)

-

Weather: ${eveningDescription}

-

Humidity: ${eveningHumidity}%

-
- `; - } + + return message; + } + + // Generate the weather message based on the weather description + const message = generateWeatherMessage(weatherDescription); + + // Display the weather message + messageContainer.innerHTML = `

${message}

`; + + container.innerHTML = ` +

Here's the weather in ${cityName}

+

${weekdays[currentDayOfWeek]}

+

Temperature: ${temperature}°C

+

Weather: ${weatherDescription}

+

Sunrise: ${sunrise.toLocaleTimeString()}

+

Sunset: ${sunset.toLocaleTimeString()}

+

Weather feels like: ${feelsLike}°C

+ `; + }) + .catch((error) => { + console.error('Error fetching weather data:', error); + }); +} + +function fetchWeatherDataBasedOnLocation() { + if ('geolocation' in navigator) { + navigator.geolocation.getCurrentPosition( + (position) => { + const latitude = position.coords.latitude; + const longitude = position.coords.longitude; + fetchWeatherDataByCoordinates(latitude, longitude); + }, + (error) => { + console.error('Error getting geolocation:', error); + container.innerHTML = '

Error getting geolocation data

'; + } + ); + } else { + console.error('Geolocation is not supported by your browser'); + container.innerHTML = '

Geolocation is not supported

'; + } +} + +// Call the function to fetch weather data based on user's location +fetchWeatherDataBasedOnLocation(); + +function fetchWeatherData() { + fetch('https://api.openweathermap.org/data/2.5/forecast?q=Stockholm,Sweden&units=metric&APPID=8fa7c461aec946fde31f330992fce9d6') + .then((response) => { + if (!response.ok) { + throw new Error('Network response was not ok'); + } + return response.json(); + }) + .then((json) => { + // Filter and group forecast data by date + const groupedForecast = json.list.reduce((result, item) => { + const date = item.dt_txt.split(' ')[0]; + if (!result[date]) { + result[date] = []; + } + result[date].push(item); + return result; + }, {}); + + // Calculate and display morning (9 AM) and evening (9 PM) temperatures for each day + for (const date in groupedForecast) { + if (groupedForecast.hasOwnProperty(date)) { + const forecastItems = groupedForecast[date]; + const morningItem = forecastItems.find((item) => item.dt_txt.includes("09:00")); + const eveningItem = forecastItems.find((item) => item.dt_txt.includes("21:00")); + + if (morningItem && eveningItem) { + const morningTemperature = morningItem.main.temp; // Temperature at 9:00 AM + const eveningTemperature = eveningItem.main.temp; // Temperature at 9:00 PM + const morningFeelsLike = morningItem.main.feels_like; // "Feels like" temperature at 9:00 AM + const eveningFeelsLike = eveningItem.main.feels_like; // "Feels like" temperature at 9:00 PM + const morningDescription = morningItem.weather[0].description; // Weather description at 9:00 AM + const eveningDescription = eveningItem.weather[0].description; // Weather description at 9:00 PM + const morningHumidity = morningItem.main.humidity; // Humidity at 9:00 AM + const eveningHumidity = eveningItem.main.humidity; // Humidity at 9:00 PM + + // Get the day of the week for the date + const weekday = new Date(date).getDay(); + + // Display the forecast for the day with time of day and "feels like" temperature + day.innerHTML += ` +
+

${weekdays[weekday]}

+

At 9 am

+

Temperature: ${morningTemperature}°C (Feels like: ${morningFeelsLike}°C)

+

Weather: ${morningDescription}

+

Humidity: ${morningHumidity}%

+

At 9 pm

+

Temperature: ${eveningTemperature}°C (Feels like: ${eveningFeelsLike}°C)

+

Weather: ${eveningDescription}

+

Humidity: ${eveningHumidity}%

+
+ `; } } - - }) - .catch((error) => { - console.error('Error fetching weather data:', error); - }); - } - - fetchWeatherData(); + } + }) + .catch((error) => { + console.error('Error fetching weather data:', error); + }); +} - function doSomething(latitude, longitude) { - console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); - } - - // Get the user's current position and call doSomething with the coordinates - navigator.geolocation.getCurrentPosition((position) => { - doSomething(position.coords.latitude, position.coords.longitude); - }); \ No newline at end of file +fetchWeatherData(); \ No newline at end of file