Friday, October 18

Yahoo Weather API with Yahoo!Query Language And JQuery

Introduction: How to link your application with Yahoo Weather API using Yahoo!Query Language (YQL) and JQuery?

What is YQL? The YQL Web Service enables applications to query, filter, and combine data from different sources across the Internet. YQL statements have a SQL-like syntax. The following YQL statement, for example, retrieves weather for a location with zipcode=60555.

select * from weather.forecast where location="60555"

To access the YQL Web Service, a Web application can call HTTP GET, passing the YQL statement as a URL parameter, for example:

http://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where location=”60555”

When it processes a query, the YQL Web Service accesses a data source on the Internet, transforms the data, and returns the results in either XML or JSON format. YQL can access several types of data sources, including Yahoo Web Services, other Web services, and Web content in formats such as HTML, XML, RSS, and Atom.

How to run YQL:

Running the following simple query, you can check the current weather forecast for a specific zipcode.
Open YQL Console (http://developer.yahoo.com/yql/console) in browser and type the sql statement.

select * from weather.forecast where location=”60555”


Then click “test” button. You can select “XML” or “JSON” as output format.






To get the current weather we’ll use the following query:

SELECT item.condition FROM weather.forecast WHERE location='60555'






Here is the output. Check the results.channel.item.condition object. It has code, date, temp and text properties. The code property is used for image. The date property indicates the last updated date, temp indicates temperature and text indicates condition.

{
 "query": {
  "count": 1,
  "created": "2013-10-18T18:37:54Z",
  "lang": "en-US",
  "diagnostics": {
   "publiclyCallable": "true",
   "url": {
    "execution-start-time": "1",
    "execution-stop-time": "78",
    "execution-time": "77",
    "content": "http://weather.yahooapis.com/forecastrss?p=60555"
   },
   "javascript": {
    "execution-start-time": "0",
    "execution-stop-time": "79",
    "execution-time": "79",
    "instructions-used": "0",
    "table-name": "weather.forecast"
   },
   "user-time": "81",
   "service-time": "77",
   "build-version": "0.2.1867"
  },
  "results": {
   "channel": {
    "item": {
     "condition": {
      "code": "26",
      "date": "Fri, 18 Oct 2013 12:51 pm CDT",
      "temp": "48",
      "text": "Cloudy"
     }
    }
   }
  }
 }
}


Complete code

<!DOCTYPE HTML>
<html>
    <head>
        <title>Weather Forecast</title>
        <style>
            #weathertext{width: 250px; border: 2px solid #cccccc; display: none;}
            #locationname{font-size: 36px; border-bottom: 1px solid #cccccc; text-transform: capitalize;color:#00ff00; font-weight: bold;}
            #temperature{font-family: arial; font-size: 24px; font-weight: bold;color:red;}
            .contents{font-family: arial;  font-size: 11px; line-height: 20px;color:black; font-weight:600;}
            #statustext{text-align: left;}
            #forecastimage{width: 120px;}
        </style>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"     type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function(){
                $('#findweather').click(function(){
                    $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%20in%20(%0A%20%20select%20id%20from%20weather.search%20where%20query%3D%22'+$('#location').val()+'%22%0A)%20limit%201&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?',function(data){
                        $('#weathertext').show();
                        $('#locationname').html($('#location').val());
                        $('#today').html(data.query.results.channel.item.condition.date);
                        $('#forecastimage').html('<img src="http://l.yimg.com/a/i/us/we/52/' + data.query.results.channel.item.condition.code + '.gif" width="34" height="34" title="' + data.query.results.channel.item.condition.code + '" />');
                        $('#temperature').html( data.query.results.channel.item.condition.temp+' &deg;F');
                        $('#condition').html( data.query.results.channel.item.condition.text);
                       
                        var winddirection=parseInt(data.query.results.channel.wind.direction);
                        var direction='';
                        switch(true)
                        {
                            case (winddirection==0):
                                direction='N';
                                break;
                            case (winddirection<90):
                                direction='NE';
                                break;
                            case (winddirection==90):
                                direction='E';
                                break;
                            case (winddirection<180):
                                direction='SE';
                                break;
                            case (winddirection==180):
                                direction='S';
                                break;
                            case (winddirection<270):
                                direction='SW';
                                break;
                            case (winddirection==270):
                                direction='W';
                                break;
                            case (winddirection<360):
                                direction='NW';
                                break;
                            case (winddirection==360):
                                direction='N';
                                break;
                        }
                      
                        $('#dirspeed').html('Wind: '+direction+' at '+data.query.results.channel.wind.speed+' mph');
                        $('#humidity').html('Humidity: '+data.query.results.channel.atmosphere.humidity+'%');
                        $('#weatherLink').html('Check ' + "<a href='"+data.query.results.channel.item.link+"'>Full Forecast</a>");



                    });
                  
                });
            });
        </script>
    </head>
    <body>
        <input type="text" id="location"/>
        <input type="button" id="findweather" value="Find weather"/><br/><br/>
        <hr/>

        <div id="weatherholder">
            <table id="weathertext">
                <tr>
                    <td colspan="2" id="locationname"></td>
                </tr>
                <tr>
                    <td id="forecastimage">
                  
                    </td>
                    <td id="statustext">
                         <span id="today"></span><br/>
                        <span id="temperature"></span><br/>

                        <span id="condition" class="contents"></span><br/>
                       <span id="dirspeed" class="contents"></span><br/>
                        <span id="humidity" class="contents"></span><br />
                       <span id="weatherLink" class="contents"></span>

                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>

Code Breakdown:

$(document).ready(function())
Everything is wrapped in the documents.ready handler. The button click event (get weather) is inside this handler.
JavaScript provides the load event for executing code when a page is rendered. This event gets triggered when the download assets such as images has completed. However, most people want their script to run as soon as the DOM hierarchy has been fully constructed. jQuery provides the .ready() for just this purpose. After DOM is ready we are calling button click event-$('#findweather').click(function()

$.getJSON(URL, Data, callback function)

The first parameter is the URL of the Server-side script. http://query.yahooapis.com/v1/public/yql

The second parameter is the request data. We build the request query with the user input (location) from location textbox  and append it to URL with ?q=”select query”. It is URLEncoded. You can copy the ‘REST QUERY’ at the bottom of the YQL Console.

The third parameter is the callback function which contains a reference to the returned JSON object(data).

Using format=json
By default the Yahoo! Web Services return output in XML format. To get output in JSON format, use the output=json parameter in the request.

getJSON Callback=?
Using JSON and callbacks, you can place the Yahoo! Web Service request inside a <script> tag, and operate on the results with a function elsewhere in the JavaScript code on the page. Using this mechanism, the JSON output from the Yahoo! Web Services request is loaded when the enclosing web page is loaded. No proxy or server is required.



Output:























































No comments:

Post a Comment