Bento/assets/js/weather.js

59 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-08-14 12:28:56 -05:00
const iconElement = document.querySelector('.weather-icon');
const tempElement = document.querySelector('.temperature-value p');
const descElement = document.querySelector('.temperature-description p');
// App data
const weather = {};
weather.temperature = {
2021-01-03 20:54:21 -06:00
unit: 'celsius',
2020-08-14 12:28:56 -05:00
};
2020-08-22 18:36:05 -05:00
// Change to 'F' for Fahrenheit
2021-07-05 22:47:21 -05:00
var tempUnit = CONFIG.weatherUnit;
2020-08-22 18:36:05 -05:00
const KELVIN = 273.15;
2020-08-14 13:20:46 -05:00
// Use your own key for the Weather, Get it here: https://openweathermap.org/
2021-07-20 20:50:46 -05:00
const key = `${CONFIG.weatherKey}`;
2020-08-14 12:28:56 -05:00
2020-08-14 12:39:30 -05:00
// Set Position function
2020-08-14 12:28:56 -05:00
setPosition();
function setPosition(position) {
2021-01-03 20:54:21 -06:00
// Here you can change your position
// You can use https://www.latlong.net/ to get it! (I use San Francisco as an example)
let latitude = 37.774929;
let longitude = -122.419418;
2020-08-14 12:28:56 -05:00
2021-01-03 20:54:21 -06:00
getWeather(latitude, longitude);
2020-08-14 12:28:56 -05:00
}
2020-08-14 12:39:30 -05:00
// Get the Weather data
2020-08-14 12:28:56 -05:00
function getWeather(latitude, longitude) {
2021-01-03 20:54:21 -06:00
let api = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`;
console.log(api);
fetch(api)
.then(function (response) {
let data = response.json();
return data;
})
.then(function (data) {
let celsius = Math.floor(data.main.temp - KELVIN);
weather.temperature.value =
tempUnit == 'C' ? celsius : (celsius * 9) / 5 + 32;
weather.description = data.weather[0].description;
weather.iconId = data.weather[0].icon;
})
.then(function () {
displayWeather();
});
2020-08-14 12:28:56 -05:00
}
2020-08-14 12:39:30 -05:00
// Display Weather info
2020-08-14 12:28:56 -05:00
function displayWeather() {
2021-07-05 22:47:21 -05:00
iconElement.innerHTML = `<img src="assets/icons/${CONFIG.weatherIcons}/${weather.iconId}.png"/>`;
2021-01-03 20:54:21 -06:00
tempElement.innerHTML = `${weather.temperature.value}°<span class="darkfg">${tempUnit}</span>`;
descElement.innerHTML = weather.description;
2020-08-14 12:28:56 -05:00
}