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
Weather Forecast with jQuery & Yahoo APIs 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 // Add the location to the page location.html(city+', '+code+''); 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 = '
'+ day +'
'+ condition + '
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 // 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.
|
Today we will be using the HTML5 Geolocation API to present the user with a personalized weather forecast.}
Read more : How to use Geolocation and Yahoo’s APIs to build a simple weather webapp
0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.