// Variables
const timeEl = document.getElementById('time');
const dateEl = document.getElementById('date');
const currentWeatherItemsEl = document.getElementById('Current-Weather-Items');
const timezone = document.getElementById('time-zone');
const countryEl = document.getElementById('country');
const weatherForecastEl = document.getElementById('weather-forecast');
const currentTempEl = document.getElementById('current-temp');
// Days and Months
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// Set time and date
setInterval(() => {
const time = new Date();
const month = time.getMonth();
const date = time.getDate();
const day = time.getDay();
const hour = time.getHours();
const hoursIn12HrFormat = hour >= 13 ? hour %12: hour;
const minutes = time.getMinutes();
const ampm = hour >=12 ? 'PM' : 'AM';
// format time to 12hour clock
timeEl.innerHTML = (hoursIn12HrFormat < 10? '0' + hoursIn12HrFormat : hoursIn12HrFormat) + ':' + (minutes < 10? '0'+minutes: minutes)+ ' ' + `${ampm}`
dateEl.innerHTML = days[day] + ', ' + date + ' ' + months[month]
}, 1000);
// Access Open Weather API and show data
getWeatherData()
function getWeatherData () {
navigator.geolocation.getCurrentPosition((success) => {
console.log(success);
let {latitude, longitude} = success.coords;
fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=minutely,hourly&units=metric&appid=${owKey}`).then(res => res.json()).then(data => {
console.log(data)
showWeatherData(data);
})
})
}
function showWeatherData (data) {
let {temp, humidity, pressure, wind_speed} = data.current;
timezone.innerHTML = data.timezone;
countryEl.innerHTML = data.lat + 'N ' + data.lon+'E'
currentWeatherItemsEl.innerHTML =
`
Temperature
${temp}°C
Humidity
${humidity}%
Pressure
${pressure}
Wind
${wind_speed} km/h
`;
// get cdn js moment package
// Current and Daily forecast
let nextDaysForecast = ''
data.daily.forEach((day, idx) => {
if(idx == 0){
currentTempEl.innerHTML = `
${window.moment(day.dt*1000).format('dddd')}
Day: ${Math.round(day.temp.day)}°C
Night: ${Math.round(day.temp.night)}°C
`
}else{
nextDaysForecast += `
${window.moment(day.dt*1000).format('ddd')}
Day: ${Math.round(day.temp.day)}°C
Night: ${Math.round(day.temp.night)}°C
`
}
})
weatherForecastEl.innerHTML = nextDaysForecast;
}