Skip to content

Instantly share code, notes, and snippets.

@savicas savicas/Project day_35
Last active Nov 25, 2019

Embed
What would you like to do?
Weather app
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<style type="text/css">
body {
margin: 1em auto;
max-width: 30em;
text-align: center;
width: 88%;
}
p {
font-size: 2em;
margin: 0 0 0.5em;
padding: 0;
}
</style>
</head>
<body>
<h1>Weather App</h1>
<div id="app">Checking the weather near you...</div>
<script>
//
// Variables
//
// Store the weather API key to a variable for easier configuration
var apiKey = '0569dfbb04164c5db60ae41fedcafc27';
// Get the #app element
var app = document.querySelector('#app');
//
// Methods
//
/**
* Sanitize and encode all HTML in a user-submitted string
* @param {String} str The user-submitted string
* @return {String} str The sanitized string
*/
var sanitizeHTML = function (str) {
var temp = document.createElement('div');
temp.textContent = str;
return temp.innerHTML;
};
/**
* Convert fahrenheit to celcius
* @param {String} temp The temperature in celcius
* @return {Number} The temperature in fahrenheit
*/
var cToF = function (temp) {
return (parseFloat(temp) * 9 / 5) + 32;
};
/**
* Render the weather data into the DOM
* @param {Object} weather The weather data object
*/
var renderWeather = function (weather) {
app.innerHTML =
'<p>' +
'<img src="https://www.weatherbit.io/static/img/icons/' + sanitizeHTML(weather.weather.icon) + '.png">' +
'</p>' +
'<p>It is currently ' + sanitizeHTML(weather.temp) + ' ℃ degrees (or '
+ cToF(sanitizeHTML(weather.temp)) + ' ℉ degrees) and '
+ sanitizeHTML(weather.weather.description).toLowerCase() + ' in ' + sanitizeHTML(weather.city_name)
//+ ', ' + sanitizeHTML(weather.state_code)
+ '.</p>';
};
//
// Inits
//
// Get the user's location by IP address
// Then, pass that into the weather API and get the current weather
fetch('https://ipapi.co/json').then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (data) {
// Pass data into another API request
// Then, return the new Promise into the stream
return fetch('https://api.weatherbit.io/v2.0/current?key=' + apiKey + '&lat=' + data.latitude + '&lon=' + data.longitude);
}).then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (data) {
console.log(data);
// Pass the first weather item into a helper function to render the UI
renderWeather(data.data[0]);
}).catch(function (error) {
// Show an error message
app.textContent = 'Unable to get weather data at this time.';
console.warn(error);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.