using api.weather.gov
Parts of this weather api to a Bootstrap card. https://api.weather.gov/gridpoints/TBW/70,97/forecast/
by grant
HTML
<script src="//code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<!--
Bootstrap docs: https://getbootstrap.com/docs
-->
<div class='card mt-3 mx-3 border-primary'>
<div class='card-body text-center'>
<div class="card-title">
<h3 id="station">Default Weatherr</h3>
</div>
<div id="myWeatherTemp"></div>
<div id="myWeatherWords"></div>
<div id="myWeatherIcon"></div>
<div class="text-muted mt-2" id="lastPull"></div>
</div>
</div>
CSS
/* using bootstrap 4.3 */
#lastPull {
font-size: 0.6rem;
}
JavaScript
//let weatherJson = "https://api.weather.gov/gridpoints/TBW/70,97/forecast/";
let weatherJson = "https://api.weather.gov/gridpoints/BOI/121,93/forecast/";
// the orignal jsfiddle
var getJSON = function(weatherJson, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', weatherJson, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
getJSON(weatherJson,
function(err, data) {
if (err !== null) {
//console.log('Something went wrong: ' + err);
} else {
// get the most current weather data (periods[0])
let forecast = data.properties.periods[0];
console.log(forecast)
$("#station").html('Boise Area');
// temperature
$("#myWeatherTemp").html(forecast.temperature + '°' + forecast.temperatureUnit);
// short Forecast (sometimes not so short)
let weatherWords = forecast.shortForecast.trim();
$("#myWeatherWords").html(weatherWords);
// now do this to get an icon
$("#myWeatherIcon").html(getWeatherIcon(weatherWords));
}
// lastly show the timestamp in the api which shows when the data was generated
let lastPull = data.properties.generatedAt;
$("#lastPull").html(myFunction(lastPull));
});
function myFunction(dateTimeString) {
const options = {
timeZone: 'America/Boise',
hour12: true,
hour: '2-digit',
minute: '2-digit'
};
let t = new Date(dateTimeString).toLocaleTimeString('en-US', options);
let d = new Date(dateTimeString).toLocaleDateString('en-US');
if (d && t) {
return ("last generated: " + d + ' ' + t);
} else {
return "";
}
}
/* What are all the possible incoming values for stringWeather? Unknown. Need to know OR need another way to identify which icon I want to use */
function getWeatherIcon(stringWeather) {
let icon = "fa-sun";
...