Getting Yahoo! Weather from JavaScript ONLY

March 18, 2013 in Dojo, JavaScript

Getting weather information in mashup applications is a very common task. As you may know, Yahoo! thankfully provided a REST API that can be used in order to get weather information using location’s zip code.
In order to invoke the Yahoo! weather REST API from JavaScript client, you can either create an XHR request that talks with a local server proxy which deals with the Yahoo! weather REST API (in order to avoid the security exception of cross-domain Ajax requests on the JavaScript client) or to use JSONP which is supported by the Yahoo! Query Language. In this post, the second approach will be illustrated because it does not require any server side work.

Dojo has a "dojo/request/script" module that can handle interactions with JSONP endpoints as follows:

require(["dojo/request/script"], function(script){
  script.get(URL, {
    jsonp: "callback",
    preventCache: true,
    timeout: 3000
  }).then(function(response) {
    // Do something with the response data
  }, function(error) {
    // Handle the error
  });
});

script object has a get API that has two parameters:
1. JSONP Service URL.
2. JSON object with optional parameters. Optional parameters can be:
a. jsonp: The name of the JSONP query parameter.
b. preventCache for cache prevention.
c. timeout: The number of milliseconds to wait for the response. If this time passes the request is canceled and the promise rejected.

For the complete list of optional parameters, check Dojo documentation here.

This is all about what you need to know about this API. Now, let’s see how to retrieve the weather information of an example place (New Era – Michigan) which has the following zip code 49446.

var errorMessage = "Unable to get weather information.";

var zipcode = "49446"; //New Era - Michigan

var query = "q=" + escape(
		  "select item from weather.forecast where location") + 
		  "=\"" + zipcode + "\"";

var endPointURL = "http://query.yahooapis.com/v1/public/yql?" + query  + 
		  "&format=json";


script.get(endPointURL, {
	jsonp: "callback",
	preventCache: true,
	timeout: 3000
}).then(function(response) {
	try {
		document.getElementById("someDivID").innerHTML = response.query.results.channel.item.description;
	} catch (exception) {
		alert(errorMessage);
	}
}, function(error) {
	alert(errorMessage + " Make sure that your device is connected to the internet.");
	console.log(error); 
});

endPointURL includes the Yahoo! REST service URL with the needed parameters and the request timeout parameter is set to 3 seconds.

Once the JSON response is retrieved successfully from the server, it will look like the following:

dojo.io.script.jsonp_dojoIoScript2._jsonpCallback({"query":{"count":1,"created":"2013-03-18T02:34:06Z","lang":"en-US","results":{"channel":{"item":{"title":"Conditions for New Era, MI at 9:33 pm EDT","lat":"43.56","long":"-86.35","link":"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html","pubDate":"Sun, 17 Mar 2013 9:33 pm EDT","condition":{"code":"33","date":"Sun, 17 Mar 2013 9:33 pm EDT","temp":"24","text":"Fair"},"description":"\n<img src=\"http://l.yimg.com/a/i/us/we/52/33.gif\"/><br />\n<b>Current Conditions:</b><br />\nFair, 24 F<BR />\n<BR /><b>Forecast:</b><BR />\nSun - Mostly Clear. High: 29 Low: 22<br />\nMon - PM Snow. High: 37 Low: 23<br />\n<br />\n<a href=\"http://us.rd.yahoo.com/dailynews/rss/weather/New_Era__MI/*http://weather.yahoo.com/forecast/USMI0597_f.html\">Full Forecast at Yahoo! Weather</a><BR/><BR/>\n(provided by <a href=\"http://www.weather.com\" >The Weather Channel</a>)<br/>\n","forecast":[{"code":"33","date":"17 Mar 2013","day":"Sun","high":"29","low":"22","text":"Mostly Clear"},{"code":"16","date":"18 Mar 2013","day":"Mon","high":"37","low":"23","text":"PM Snow"}],"guid":{"isPermaLink":"false","content":"USMI0597_2013_03_18_7_00_EDT"}}}}}});

This is why using the response.query.results.channel.item.description long expression will get the required weather information from the returned service response.

One comment on “Getting Yahoo! Weather from JavaScript ONLY

  1. Jayson Ward on said:

    When I use this, I get a “Syntax Error: invalid label” error in Firefox and an “Unexpected token :” error in Chrome. Any ideas?

Leave a reply

Your email address will not be published. Required fields are marked *

364,544 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha