Skip to content

Instantly share code, notes, and snippets.

@theptrk
Last active June 3, 2020 00:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theptrk/331fa4a778925276e858130330113056 to your computer and use it in GitHub Desktop.
Save theptrk/331fa4a778925276e858130330113056 to your computer and use it in GitHub Desktop.
This uses the OpenWeather current weather data API: https://openweathermap.org/current
<!DOCTYPE html>
<html>
<head>
<title>Open Weather API</title>
<style type="text/css">
pre {
background-color: #f1f1f1;
padding: 5px;
margin: 5px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Open Weather API</h1>
<form id="weather_form">
<input type="text" name="city" id="city" required>
<button type="submit">
Get Weather
</button>
</form>
<div>
<h2 id='temperature'></h2>
<div id="output"></div>
<div id="full_response" class="json"></div>
</div>
</body>
<script type="text/javascript">
const $form = document.getElementById("weather_form")
const $city = document.getElementById("city")
$form.addEventListener("submit", handleFormSubmit);
var innerHTML = innerHTMLHelper();
function handleFormSubmit(e) {
e.preventDefault();
console.log("getting weather")
var city = $city.value;
if (city.length === 0) {
return "invalid location input"
}
requestWeather(city, renderWeather)
}
function requestWeather(city, cb) {
const API_KEY = "<your_api_key>";
const url = "http://api.openweathermap.org/data/2.5/weather?" +
"&q=" + city +
"&appid=" + API_KEY +
"&units=imperial";
getJSON(url, cb);
}
function renderWeather(data) {
var main = data.response.main;
var condition = data.response.weather[0];
var output = `<span>
Conditions: ${condition.main} -
feels like ${main.feels_like}&#176; -
humidity ${main.humidity} -
high ${main.temp_max}&#176; -
low ${main.temp_min}&#176;
</span>`
var iconBase = "http://openweathermap.org/img/wn/";
var iconSrc = iconBase + condition.icon + ".png";
var icon = `<img src="${iconSrc}"/>`
var temperature = `${icon} Temperature: ${main.temp}&#176;`
innerHTML("output", output)
innerHTML("temperature", temperature)
var json = JSON.stringify(data, null, 2);
innerHTML("full_response", `<pre>${json}</pre>`)
}
function getJSON(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url)
xhr.onload = function() {
cb({
status: this.status,
response: JSON.parse(this.response)
})
}
xhr.send();
}
function innerHTMLHelper() {
var memo = {}
return function(id, html) {
if (!memo[id]) {
memo[id] = document.getElementById(id)
}
memo[id].innerHTML = html
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment