Using the Open Weather API (https://openweathermap.org/current#geo), display the weather for the user
A Pen by Stephen Fox on CodePen.
Using the Open Weather API (https://openweathermap.org/current#geo), display the weather for the user
A Pen by Stephen Fox on CodePen.
<main class="weather clear-fix"> | |
<div id="widget"> | |
Locating... | |
</div> | |
<section class="subtext"> | |
<p>Latitude: <span class="lat-text"></span> </p> | |
<p>Longitude: <span class="lon-text"></span> </p> | |
</section> | |
</main> | |
<footer> | |
<!-- Show props to OpenWeather --> | |
</footer> |
if ("geolocation" in navigator) { | |
app() | |
} else { | |
// show "get a better browser" | |
} | |
const apiToken = ; | |
const tokens = Object.freeze({ | |
openWeather: "c956be2393a90fa93862362987fc9491", | |
apixu: "023d66b6a2824a3e95764726172302" | |
}); | |
const subtextElement = document.querySelector('.subtext'); | |
function craftUrl({latitude, longitude}) { | |
return `http://api.openweathermap.org/data/2.5/weather?units=metric&lat=${latitude}&lon=${longitude}&APPID=${apiToken}` | |
} | |
function renderCoordinates(latitude, longitude) { | |
const lat = Number(latitude).toFixed(2); | |
const long = Number(longitude).toFixed(2); | |
document.querySelector('.lat-text').innerHTML = lat + "°"; | |
document.querySelector('.lon-text').innerHTML = long + "°"; | |
} | |
function presentLocalWeather({coords}) { | |
// properties are | |
// latitute, longitude, and accuracy | |
console.log("Got coordinates", coords); | |
renderCoordinates(coords.latitude, coords.longitude); | |
// ping open-weather | |
const xhr = new XMLHttpRequest(); | |
xhr.open('GET', craftUrl(coords), true); | |
xhr.send(); | |
xhr.onreadystatechange = function(e) { | |
if (xhr.readyState == 4 && xhr.status == 200) { | |
const response = JSON.parse(xhr.responseText); | |
console.log(response); | |
document.getElementById('widget').innerHTML = response; | |
} | |
} | |
}; | |
function handleError() { | |
console.log("An error occurred"); | |
console.error(arguments[0]); | |
}; | |
function app() { | |
const settings = { | |
enableHighAccuracy: true, | |
timeout: 5000, | |
maximumAge: 0 | |
}; | |
navigator.geolocation.getCurrentPosition(presentLocalWeather, handleError, settings); | |
} |
/* reset styles */ | |
html, body { | |
height: 100%; | |
margin: 0; | |
max-height: 600px; | |
display: block; | |
} | |
.clear-fix:after { | |
content: " "; | |
visibility: hidden; | |
display: block; | |
height: 0; | |
clear: both; | |
} | |
/* actual styles */ | |
.weather { | |
text-align: center; | |
margin: auto; | |
width: 300px; | |
font-size: 18pt; | |
/* Show us the selector works */ | |
background-color: pink; | |
} | |
@media (max-width: 500) { | |
* { | |
background-color: blue; | |
} | |
} |