Today we will be using the HTML5 geolocation API to present the user with a personalized weather forecast. Using jQuery, we will issue AJAX request to two of Yahoo’s popular APIs to obtain additional geographical information and a weather forecast. This example also makes use of the wonderful climacons icon set.
Obtaining an Application Key
Yahoo provides a large collection of useful APIs that are free for developers to use. The requirement is that you register your application with through their developer dashboard. The registration is simple and straightforward, and as a result you obtain an application id (look for it under the title of your application). You are going to need this later in the tutorial, but first let’s see how everything would work together.
The Idea
Here is what we need to do in order to display our weather forecast:
- First we’ll use the Geolocation API supported by modern browsers. The API will prompt the user to authorize location access and will return a set of GPS coordinates;
- Next, we will issue a request to Yahoo’s PlaceFinder API, passing the above coordinates. This will give us the name of the city and country, and a woeid – a special ID used to identify the city in weather forecasts;
- Finally, we will issue a request to Yahoo’s Weather API with that woeid. This will give us current weather conditions, as well as a forecast for the rest of the current and the next day.
Great! We are now ready for the HTML.
The HTML
We will start with a blank HTML5 document, and we will add a reference to our stylesheet to the head section, along with two fonts from Google’s Webfonts library. In the body we will add a h1 header and markup for the weather forecast slider.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Weather Forecast with jQuery & Yahoo APIs | Tutorialzine Demo</title>
<!-- The stylesheet -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!-- Google Fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Playball|Open+Sans+Condensed:300,700" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>Weather Forecast</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, turn.js and our own script.js -->
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
Before the closing body tag we are adding the latest version of jQuery and our script.js file, which we are discussing in the following sections.
The JavaScript
The first step is to define two configuration variables in /assets/js/script.js:
var APPID = ''; // Your Yahoo Application ID var DEG = 'c'; // c for celsius, f for fahrenheit
These are passed as parameters with the AJAX requests for the location and weather APIs as you will see in a moment.
Following the outline in the idea section, we should now look into using the HTML5 Geolocation API to obtain a set of GPS coordinates. This API is supported by all new browsers including IE9 and mobile devices. To use it, we need to test whether the global navigator object has a geolocation property. If it does, we call its getCurrentPosition method passing two event handling functions for success and failure. Here is the relevant code from script.js that does this:
// Does this browser support geolocation?
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
}
else{
showError("Your browser does not support Geolocation!");
}
function locationSuccess(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// We will make further requests to Yahoo's APIs here
}
function locationError(error){
switch(error.code) {
case error.TIMEOUT:
showError("A timeout occured! Please try again!");
break;
case error.POSITION_UNAVAILABLE:
showError('We can\'t detect your location. Sorry!');
break;
case error.PERMISSION_DENIED:
showError('Please allow geolocation access for this to work.');
break;
case error.UNKNOWN_ERROR:
showError('An unknown error occured!');
break;
}
}
function showError(msg){
weatherDiv.addClass('error').html(msg);
}
The locationSuccess function is where we will be issuing requests to Yahoo’s APIs in a moment. The locationError function is passed an error object with the specific reason for the error condition. We will use a showError helper function to display the error messages on the screen.
The full version of locationSuccess follows:
function locationSuccess(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// Yahoo's PlaceFinder API http://developer.yahoo.com/geo/placefinder/
// We are passing the R gflag for reverse geocoding (coordinates to place name)
var geoAPI = 'http://where.yahooapis.com/geocode?location='+lat+','+lon+'&flags=J&gflags=R&appid='+APPID;
// Forming the query for Yahoo's weather forecasting API with YQL
// http://developer.yahoo.com/weather/
var wsql = 'select * from weather.forecast where woeid=WID and u="'+DEG+'"',
weatherYQL = 'http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent(wsql)+'&format=json&callback=?',
code, city, results, woeid;
// Issue a cross-domain AJAX request (CORS) to the GEO service.
// Not supported in Opera and IE.
$.getJSON(geoAPI, function(r){
if(r.ResultSet.Found == 1){
results = r.ResultSet.Results;
city = results[0].city;
code = results[0].statecode || results[0].countrycode;
// This is the city identifier for the weather API
woeid = results[0].woeid;
// Make a weather API request (it is JSONP, so CORS is not an issue):
$.getJSON(weatherYQL.replace('WID',woeid), function(r){
if(r.query.count == 1){
// Create the weather items in the #scroller UL
var item = r.query.results.channel.item.condition;
addWeather(item.code, "Now", item.text + ' <b>'+item.temp+'°'+DEG+'</b>');
for (var i=0;i<2;i++){
item = r.query.results.channel.item.forecast[i];
addWeather(
item.code,
item.day +' <b>'+item.date.replace('\d+$','')+'</b>',
item.text + ' <b>'+item.low+'°'+DEG+' / '+item.high+'°'+DEG+'</b>'
);
}
// Add the location to the page
location.html(city+', <b>'+code+'</b>');
weatherDiv.addClass('loaded');
// Set the slider to the first slide
showSlide(0);
}
else {
showError("Error retrieving weather data!");
}
});
}
}).error(function(){
showError("Your browser does not support CORS requests!");
});
}
The PlaceFinder API returns its results as plain JSON. But as it is on a different domain, only browsers that support CORS (cross origin resource sharing) will be able to retrieve it. Most major browsers that support geolocation also support CORS, with the exception of IE9 and Opera, which means that this example won’t work there.
Another thing to consider is that the weather API returns only two days of forecasts, which somewhat limits the utility of our web app, but unfortunately there is no way around it.
We are only using the Weather API for temperature data, but it provides additional information that you might find useful. You can play with the API and browse the responses in the YQL console.
After we retrieve the weather data, we call the addWeather function, which creates a new LI item in the #scroller unordered list.
function addWeather(code, day, condition){
var markup = '<li>'+
'<img src="assets/img/icons/'+ weatherIconMap[code] +'.png" />'+
' <p class="day">'+ day +'</p> <p class="cond">'+ condition +
'</p></li>';
scroller.append(markup);
}
Now we need to listen for clicks on the previous / next arrows, so we can offset the slider to reveal the correct day of the forecast.
/* Handling the previous / next arrows */
var currentSlide = 0;
weatherDiv.find('a.previous').click(function(e){
e.preventDefault();
showSlide(currentSlide-1);
});
weatherDiv.find('a.next').click(function(e){
e.preventDefault();
showSlide(currentSlide+1);
});
function showSlide(i){
var items = scroller.find('li');
// Exit if the requested item does not exist,
// or the scroller is currently being animated
if (i >= items.length || i < 0 || scroller.is(':animated')){
return false;
}
// The first/last classes hide the left/right arrow with CSS
weatherDiv.removeClass('first last');
if(i == 0){
weatherDiv.addClass('first');
}
else if (i == items.length-1){
weatherDiv.addClass('last');
}
scroller.animate({left:(-i*100)+'%'}, function(){
currentSlide = i;
});
}
With this our simple weather web app is complete! You can see everything together in /assets/js/script.js. We won't be discussing the styling here, but you can read through /assets/css/styles.css yourself.
Done!
In this example you learned how to use the HTML5 geolocation with Yahoo's Weather and Places APIs to present a location-aware weather forecast. It works on most modern web browsers and mobile devices.





15 Comments
Great tutorial but somehow it doesn't work in mozilla and chome. It never stops loading.
The problem is now fixed. It appears that the weather API does not have support for some cities and returns an error, which I hadn't accounted for. Now at least it shows a friendly error message instead of getting stuck in load mode. The download is also updated with the new version of the script.
Thanks for this awesome tutorial
Really just what I needed, Thank you so much.
Love this tutorial, Thanks!
WOW!!
I was able to modify your code by translating forecasts into Italian, and by taking the coordinates from my DB, instead of exploiting the browser detection.
Thank you a lot!!
Nice tutorial!! How would you add the option to change the location if it was incorrect?
The easiest solution would be to give an option to manually enter a city. You will need to use the Places API with the typed value and remove the R flag for reverse geocoding.
Demo is stuck on loading...
Thanks for the great tutorial! It works on localhost but when I try to upload it I get a 403 does it need any particular configuration? Thanks in advance
Something different is at play here. Are you looking at the correct URL?
Hey Martin'. Just nice idea !
Well, I guess he's always getting stuck in load mode and it shows no error message.
(My city is Paris!)
Thanks man!
I have a issue with the geolocation is says "Please allow geolocation access for this to work." but never prompts to allow it.... I am running Safari 5.2 and 10.8 beta
Any ideas?
You have probably disabled geolocation globally. This happened to me when testing on iOS. Turning it on in the settings will fix it.
Great tutorial, but the demo can't detech my location ( VietNam ) , T_T