Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WeathertheWeatherApp #430

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
18 changes: 12 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
# Weather App
Project: WeatherTheWeatherApp

Replace this readme with your own information about your project.
WeatherTheWeatherApp is a weather application that retrieves and displays real-time data for Stockholm. It fetches and displays the current location, temperature, weather condition, sunrise, and sunset times. It shows the weather forecast for today and the next four days, including daily min and max temperatures. The app visually changes images and background styles based on whether it’s clear, cloudy, or rainy, and whether it’s day or night.

Start by briefly describing the assignment in a sentence or two. Keep it short and to the point.
Challenges Encountered
- The initial challenge involved successfully retrieving data from the OpenWeatherMap API. Utilizing console.log helped me identifying the structure of the API response.
- Converting UNIX timestamps for sunrise and sunset times into a readable format was a challenge, but resolved this using a the function, convertUnixToTime.
- I found implementing some sort of logic to change the background and images based on weather conditions and the time of day very complex. For this, I use a switch statement and various condition checks to ensure the app responded accurately to different weather scenarios/time of day.

## The problem
If given more time, I would:

Describe how you approached to problem, and what tools and techniques you used to solve it. How did you plan? What technologies did you use? If you had more time, what would be next?
- Create a helper function to streamline the code that handles image and background changes, as it now includes a lot of redundancy and repetetive code.
- Implement weather condition icons for each day in the forecast.
- Refine the styling to better align with the Figma design layout.
- Enhance responsiveness for a wider range of screen sizes.

## View it live

Every project should be deployed somewhere. Be sure to include the link to the deployed project so that the viewer can click around and see what it's all about.
https://master--weathertheweatherapp.netlify.app
Binary file added assets/.DS_Store
Binary file not shown.
Binary file added assets/design-2/Clouds.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-2/Moon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-2/broken-clouds.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-2/rain.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-2/sun-100.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assets/design-2/sun.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
48 changes: 48 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<!-- import font-family -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap"
rel="stylesheet">
<title>WeathertheweatherApp</title>
</head>

<body>
<main>
<section class="weather-card">
<div class="location-card" id="locationCard">
<div class="temp-container">
<img src="assets/design-2/sun.png" alt="sun" id="sun">
<img src="assets/design-2/Clouds.png" id="cloudsImg" alt="clouds-img">
<img src="assets/design-2/broken-clouds.png" id="brokenCloudsImg" alt="broken-clouds-img">
<img src="assets/design-2/rain.png" id="rainImg" alt="rain-img">
<img src="assets/design-2/Moon.png" id="moonImg" alt="moon-img">
<p class="temp" id="temp">Temp</p>
<p class="location" id="location">location</p>
<p class="condition" id="condition">condition</p>
</div>
<div class="suntime-container">
<p class="sunrise" id="sunriseID">sunrise</p>
<p class="sunset" id="sunsetID">sunset</p>
</div>
</div>

</div>
<div class="forecast-card">
<ul class="forecast" id="forecastID">forecast</ul>
</div>
</section>

</main>

<script src="script.js"></script>
</body>

</html>
236 changes: 236 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@

//STEP 1: constructing the BASE URL
const BASE_URL = 'https://api.openweathermap.org/data/2.5/weather?q=Stockholm,Sweden&units=metric&appid='
const API_KEY = '1bd3fe8b6571a9e92c6d24232e62bdc8'

const URL = `${BASE_URL}${API_KEY}`

//STEP 2: URL for Weather Forecast
const FORECAST_URL = 'https://api.openweathermap.org/data/2.5/forecast?q=Stockholm,Sweden&units=metric&appid='

const forecastURL = `${FORECAST_URL}${API_KEY}`

// DOM Selectors
const weatherLocation = document.getElementById("location");
const temperature = document.getElementById("temp");
const weatherCondition = document.getElementById("condition");
const sunriseDisplay = document.getElementById("sunriseID");
const sunsetDisplay = document.getElementById("sunsetID");
const forecast = document.getElementById("forecastID")
const locationCard = document.getElementById("locationCard")
//DOM Selectors - Images
const sunImg = document.getElementById("sun");
const cloudsImg = document.getElementById("cloudsImg");
const rainImg = document.getElementById("rainImg");
const brokenCloudsImg = document.getElementById("brokenCloudsImg");
const moonImg = document.getElementById("moonImg")

//FUNCTIONS
//Function to handle errors
const handleError = (errorMessage) => {
console.error('Error fetching data:', errorMessage);
forecast.innerHTML = "Unable to retrieve weather data.";
};

// Function to convert UNIX timestamp to readable time format
const convertUnixToTime = (unixTimestamp) => {
const date = new Date(unixTimestamp * 1000);
//Round the number to a format without seconds
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// Function to format timestamp to date string (YYYY-MM-DD)
const formatDate = (timestamp) => {
const date = new Date(timestamp * 1000);
return date.toISOString().split('T')[0]; // Get only the date part
};

// Function to get day of the week from date string
const getDayOfWeek = (dateString) => {
const date = new Date(dateString);
const daysOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
return daysOfWeek[date.getDay()];
};

// Initialize an object to hold daily min and max temps
const dailyTemps = {};

//Fetching data from the IPA for current weather
fetch(URL)
.then(response => response.json())
.then(data => {
console.log(data);

const stockholm = data.name;
const stockholmTemp = data.main.temp;
const roundedTemp = Math.round(stockholmTemp);
const displayCondition = data.weather[0].description;

//changing the innerHTML for city, temp and condition.
weatherLocation.innerText = `${stockholm}`;
temperature.innerHTML =
`<span class="temp-number">${roundedTemp}</span><span class="temp-unit">°C</span>`;
weatherCondition.innerText = `${displayCondition}`;

//Get the sunrise and sunset
const sunriseTime = convertUnixToTime(data.sys.sunrise);
const sunsetTime = convertUnixToTime(data.sys.sunset);

// Display sunrise and sunset times in innerText
sunriseDisplay.innerText = `Sunrise ${sunriseTime}`;
sunsetDisplay.innerText = `Sunset ${sunsetTime}`;

// Create a new Date object
const date = new Date();

// Get the time offset for Stockholm (CET/CEST: Central European Time/ Central European Summer Time)
const options = {
timeZone: "Europe/Stockholm",
hour: "2-digit",
};

const stockholmTime = date.toLocaleTimeString("sv-SE", options);

// Hide all images
sunImg.classList.add("hidden");
cloudsImg.classList.add("hidden");
rainImg.classList.add("hidden");
brokenCloudsImg.classList.add("hidden");
moonImg.classList.add("hidden");

// Change image & background if condition is sunny/cloudy and if the time is night/day
switch (true) {
case displayCondition.includes("clear"):
if (stockholmTime >= 6 && stockholmTime < 21) {
// Daytime clear weather
sunImg.classList.remove("hidden");
sunImg.classList.add("visible");
moonImg.classList.add("hidden");
locationCard.classList.remove("location-card-night");
locationCard.classList.add("location-card");
} else {
// Nighttime clear weather
moonImg.classList.remove("hidden");
moonImg.classList.add("visible");
sunImg.classList.add("hidden");
locationCard.classList.add("location-card-night");
}
break;

case displayCondition.includes("cloud"):
if (stockholmTime >= 6 && stockholmTime < 21) {
// Daytime cloudy weather
cloudsImg.classList.remove("hidden");
cloudsImg.classList.add("visible");
moonImg.classList.add("hidden");
locationCard.classList.remove("location-card-night");
locationCard.classList.add("location-card");
} else {
// Nighttime cloudy weather
moonImg.classList.remove("hidden");
moonImg.classList.add("visible");
cloudsImg.classList.add("hidden");
locationCard.classList.add("location-card-night");
}
break;

case displayCondition.includes("rain"):
if (stockholmTime >= 6 && stockholmTime < 21) {
// Daytime rainy weather
rainImg.classList.remove("hidden");
rainImg.classList.add("visible");
moonImg.classList.add("hidden");
locationCard.classList.remove("location-card-night");
locationCard.classList.add("location-card-rainy");
} else {
// Nighttime rainy weather
moonImg.classList.remove("hidden");
moonImg.classList.add("visible");
rainImg.classList.add("hidden");
locationCard.classList.add("location-card-night");
}
break;

case displayCondition.includes("broken"):
if (stockholmTime >= 6 && stockholmTime < 21) {
// Daytime broken clouds
brokenCloudsImg.classList.remove("hidden");
brokenCloudsImg.classList.add("visible");
moonImg.classList.add("hidden");
locationCard.classList.remove("location-card-night");
locationCard.classList.add("location-card");
} else {
// Nighttime broken clouds
moonImg.classList.remove("hidden");
moonImg.classList.add("visible");
brokenCloudsImg.classList.add("hidden");
locationCard.classList.add("location-card-night");
}
break;

default:
locationCard.classList.add("location-card");
moonImg.classList.add("hidden");
}

})
.catch(error => handleError(error));


// Fetching data from the forecastURL
fetch(forecastURL)
.then(response => response.json())
.then(data => {
console.log(data);

// Iterate through the weather forecast
data.list.forEach((forecast) => {
const date = formatDate(forecast.dt);
const minTemp = forecast.main.temp_min;
const maxTemp = forecast.main.temp_max;

// Initialize the entry for the date if it doesn't exist
if (!dailyTemps[date]) {
dailyTemps[date] = { min: minTemp, max: maxTemp };
} else {
// Update the min and max temps for the day
dailyTemps[date].min = Math.min(dailyTemps[date].min, minTemp);
dailyTemps[date].max = Math.max(dailyTemps[date].max, maxTemp);
}
});

// Extract the next four days' temperatures and convert date to day name
const nextFourDays = Object.entries(dailyTemps)
//Getting the current day + the following 4 days
.slice(0, 5)
.map(([date, temps]) => ({
date: getDayOfWeek(date),
min: temps.min,
max: temps.max,
}));

// Render the forecast data in the browser
renderForecast(nextFourDays);
})
.catch(error => handleError(error));


// Function to render forecast data in the browser
const renderForecast = (forecastData) => {
forecast.innerHTML = "";
let forecastContent = "";

forecastData.forEach(day => {
forecastContent +=
`<li class="forecast-item">
<span class="day-date">${day.date}</span>
<span class="temp-info">${Math.round(day.min)}° / ${Math.round(day.max)}°C</span>
</li>`;
});

forecast.innerHTML = forecastContent;
};




Loading