Open Weather Map ex.
by gavinfoley
HTML
<header>
<h1>Weather Forecast<span id="city"></span></h1>
</header>
<div id="weather">
<ul id="scroller">
<!-- The forecast items will go here -->
</ul>
<a href="#" class="arrow previous">Previous</a>
<a href="#" class="arrow next">Next</a>
</div>
<p class="location"></p>
<div id="clouds"></div>
<!-- JavaScript includes - jQuery, moment.js and our own script.js -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>
JavaScript
$(function(){
/* Configuration */
var DEG = 'c'; // c for celsius, f for fahrenheit
var weatherDiv = $('#weather'),
scroller = $('#scroller'),
location = $('p.location');
// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else{
showError("Your browser does not support Geolocation!");
}
// Get user's location, and use OpenWeatherMap
// to get the location name and weather forecast
function locationSuccess(position) {
try{
console.log(position);
// Retrive the cache
var cache = localStorage.weatherCache && JSON.parse(localStorage.weatherCache);
var d = new Date();
// If the cache is newer than 30 minutes, use the cache
if(cache && cache.timestamp && cache.timestamp > d.getTime() - 30*60*1000){
// Get the offset from UTC (turn the offset minutes into ms)
var offset = d.getTimezoneOffset()*60*1000;
var city = cache.data.city.name;
var country = cache.data.city.country;
$.each(cache.data.list, function(){
// "this" holds a forecast object
// Get the local time of this forecast (the api returns it in utc)
var localTime = new Date(this.dt*1000 - offset);
addWeather(
this.weather[0].icon,
moment(localTime).calendar(), // We are using the moment.js library to format the date
this.weather[0].main + ' <b>' + convertTemperature(this.main.temp_min) + '°' + DEG +
' / ' + convertTemperature(this.main.temp_max) + '°' + DEG+'</b>'
);
});
// Add the location to the page
...