11 October, 2012

Geolocation and Yahoo’s APIs to make weather app

0 Flares Facebook 0 Twitter 0 Google+ 0 Pin It Share 0 Email -- Email to a friend Buffer 0 Buffer 0 Flares ×

Today we will make a simple webapp for Geolocation to check your current weather status.Using jQuery, we will issue AJAX request to two of Yahoo’s popular APIs to obtain additional geographical information and a weather forecast.this can be done by using yahoo’s apis.Yahoo provides a large collection of useful APIs that are free for developers to use.To get this feature you just have to register your application at yahoo’s dashboard.Now we will see how this works.

starkbook-geolocation-webapp

How to set it up

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.

Workout:-

index.html
Let’s take a look of html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
< !DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Starkbook Demo | Weather Forecast with jQuery &amp; Yahoo APIs
</title>

        <!-- The stylesheet -->
        <link rel="stylesheet" href="css/stark.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="js/script.js"></script>

    </body>
</html>

Script.js
Before stating about javascript we have to define two variable for App id and Temprature.

1
2
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.

To check that your browser support geolocation feature or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 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 full version of locationSuccess follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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&lt;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!");
    });

}

After we retrieve the weather data, we call the addWeather function, which creates a new LI item in the #scroller unordered list.

1
2
3
4
5
6
7
8
9
function addWeather(code, day, condition){

    var markup = '<li>'+
        '<img src="img/icons/'+ weatherIconMap[code] +'.png" />'+
        ' <p class="day">'+ day +'</p> <p class="cond">'+ condition +
        '</p></li>';

    scroller.append(markup);
}

With These lines of code our webapp for weather checking is ready for use.You can see whole code in demo version.

Harry Saggu

Harry Saggu

Admin at Starkbook
♛ A Web-designer, front-end developer and founder of Starkbook Webdesign Blog. I love working with every creative things and doing it right way. So I always try to provide best designing stuff to our readers.
Harry Saggu

Join Our Free Email Newsletter

To Get A Free E-Book:"The Wordpress Anthology" Now !

Web Designers Ultimate 3 Book Bundle

Get It Now*

Start Your Website
With Wordpress.

Leave a Reply

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

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>

Starkbook Webdesign Blog
  • Join Our Free Email Updates
  • Get Webdesigning Stuff Direct In Your Inbox
  • You Will Get Many Code-Snippets, Freebies, Wordpress Themes, Web-Designing Stuff etc. On Starkbook
  • Stay Always Conneted With Starkbook

Subscribe for Free Email Updates

Get our latest updates direct in your inbox.Just enter your email address above...

Your privacy and email address are safe with us!
Ver peliculas online
0 Flares Facebook 0 Twitter 0 Google+ 0 Pin It Share 0 Email -- Email to a friend Buffer 0 Buffer 0 Flares ×