/*
* Weather API can be found here -> WeatherAPI.com
*/
// Use an IIFE to prevent pollution of the global namespace
(() => {
// Select the container element to display the weather data
const weatherContainer = document.querySelector('#weather-container');
// Define the number of days to show in the forecast
const number_of_days = 3;
// Set the options for the RapidAPI fetch request
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '538cfb860dmshc9f516bd834ae95p106254jsn94d12e1779c7',
'X-RapidAPI-Host': 'weatherapi-com.p.rapidapi.com'
}
};
// Add a heading to the container element
let heading = `<h1>Weather for Livonia, Michigan</h1>`;
weatherContainer.appendChild(document.createRange().createContextualFragment(heading));
// Function to display the current weather
const current_weather = (data) => {
// Extract the relevant data from the response
let temp_f = data.current.temp_f;
let wind_mph = data.current.wind_mph;
let wind_gust = data.current.gust_mph;
// Create the HTML to display the current weather data
const weatherHTML = `
<p>Current Temp is ${temp_f} F and the wind is ${wind_mph} mph with gusts up to ${wind_gust} mph;</p>`;
// Add the weather data to the container element
weatherContainer.appendChild(document.createRange().createContextualFragment(weatherHTML));
}
// Function to display the forecast
const forecast = (data) => {
// Extract the relevant data from the response
const forecastDay = data.forecast.forecastday;
// Create the HTML for the forecast heading
const future = `<h2>${number_of_days} Day Forecast</h2>`;
weatherContainer.appendChild(document.createRange().createContextualFragment(future));
// Loop through each day in the forecast and display the relevant data
for (let i = 0; i < forecastDay.length; i++) {
let weatherDate = forecastDay[i].date;
let day = forecastDay[i].day;
const { maxtemp_f, mintemp_f, daily_chance_of_rain, daily_chance_of_snow} = day;
const weatherForecastHTML = `
<p>${weatherDate} the high for today will be ${maxtemp_f} F and
the low will be ${mintemp_f}</p>
<p>Chance of rain ${daily_chance_of_rain}% or chance of snow ${daily_chance_of_snow}%</p>
`;
weatherContainer.appendChild(document.createRange().createContextualFragment(weatherForecastHTML));
}
}
// Function to fetch the weather data and display it
const getWeatherData = () => {
fetch('https://weatherapi-com.p.rapidapi.com/forecast.json?q=42.36%2C%20-83.37&days=' + number_of_days, options)
.then(response => response.json())
.then(data => {
// Call the functions to display the weather data
current_weather(data);
forecast(data);
})
.catch(err => console.error(err));
};
// Call the function to fetch and display the weather data
getWeatherData();
})();