jQuery weather widget

Tuesday, 24 November 2009



In this tutorial we are going to build a jQuery weather widget. This widget is pure javascript and requires no back-end/server so you can place it on your blog or anywhere you like.

Please note: Information in this widget should not be taken as accurate under any circumstance and should not be used to make any decisions in any circumstance. It is purely a toy. We make no claim to its accuracy for any purpose.


You can get the code for this tutorial here.

The widget makes two main calls using JSON to retrieve the users geolocation and then to retrieve the local weather for that location. It also uses the jQuery cookie plugin to remember the details so that it doesn't need to make these calls each time the page reloads.

The two JSON calls are to the geoPlugin site and then to the geonames weather webservice using the retrieved longitude and latitude coordinates. Please check the terms and conditions from their site if you want to use this widget on your own site. It also uses Googles weather images.

Let's look at the first part of the javascript code. We begin with the jQuery document ready function:

$("document").ready(function() {
     if ($.cookie('loc_longitude') && $.cookie('loc_latitude')) {
          getWeather();
     } else {
          $.getJSON("http://www.geoplugin.net/json.gp?callback=?", function(data) {
                eval(data);
          });
     }
});

It begins by checking if the geocordinates for this user have been set for this user. If not it calls the geoplugin site to retrieve geolocation details.

function geoPlugin(data) {
     $.cookie('loc_latitude', data.geoplugin_latitude, {expires: 7}); 
     $.cookie('loc_longitude', data.geoplugin_longitude, {expires: 7});
     $.cookie('loc_country', data.geoplugin_countryName, {expires: 7});
     $.cookie('loc_region', data.geoplugin_region, {expires: 7});
     $.cookie('loc_city', data.geoplugin_city, {expires: 7});
     $.cookie('loc_country_code', data.geoplugin_countryCode, {expires: 7});
     getWeather();
}

The eval function above calls the geoPlugin function and sets the geolocation details in the cookie, this will be used in the getWeather function which you will notice is called above if the location details are already set.

function getWeather() {
     var latitude = $.cookie('loc_latitude');
     var longitude = $.cookie('loc_longitude');

     var loc_conditions = $.cookie('loc_conditions');
     var loc_conditions_img = $.cookie('loc_conditions_img');
     var loc_temp = $.cookie('loc_temp');
     var loc_humidity = $.cookie('loc_humidity');

     if (loc_conditions && loc_conditions_img) {
          setConditions(loc_conditions, loc_conditions_img, loc_temp, loc_humidity);
     } else {
          var url = "http://ws.geonames.org/findNearByWeatherJSON?lat=" + latitude + "&lng=" + longitude + "&callback=?";
          $.getJSON(url, function(data) {
               var clouds = data.weatherObservation.clouds;
               var weather = data.weatherObservation.weatherCondition;
               var temp = data.weatherObservation.temperature;
               var humidity = data.weatherObservation.humidity;
   
               var conditions_img = getConditions(clouds, weather);
   
               var conditions = '';
               if (weather == 'n/a') {
                    if (clouds == 'n/a') {
                         conditions = 'fine';
                    } else {
                         conditions = clouds;
                    }
               } else {
                    conditions = weather;
               }
   
                    $.cookie('loc_conditions', conditions); 
                    $.cookie('loc_conditions_img', conditions_img); 
                    $.cookie('loc_temp', temp); 
                    $.cookie('loc_humidity', humidity); 
                    setConditions(conditions, conditions_img, temp, humidity);
          });
     }
}

The getWeather function starts by retrieving all of the geolocation details from the cookie. It then checks the cookie to see if the temperature details have been set in the cookie, if they have it simply goes ahead and displays all the information in the widget by calling the setConditions function.

If the temperature details haven't been set in the cookie it then calls the JSON weather service using the latitude and longitude details from the first JSON call. It then calls the getConditions function to retrieve the correct image corresponding to the current weather condition.

function getConditions(clouds, weather) {
     if (weather == 'n/a') {
          switch (clouds) {
               case 'n/a':
                    return 'sunny.gif';
               case 'clear sky':
                    return 'sunny.gif';
               case 'few clouds':
                    return 'partly_cloudy.gif';
               case 'scattered clouds':
                    return 'partly_cloudy.gif';
               case 'broken clouds':
                    return 'partly_cloudy.gif';
               default:
                    return 'cloudy.gif';
          }
     } else {
          weather = weather.replace('light ', '').replace('heavy ', '').replace(' in vicinity', '');
          switch(weather) {
               case 'drizzle':
                    return 'rain.gif';
               case 'rain':
                    return 'rain.gif';
               case 'snow':
                    return 'snow.gif';
               case 'snow grains':
                    return 'sleet.gif';
               case 'ice crystals':
                    return 'icy.gif';
               case 'ice pellets':
                    return 'icy.gif';
               case 'hail':
                    return 'sleet.gif';
               case 'small hail':
                    return 'sleet.gif';
               case 'snow pellets':
                    return 'sleet.gif';
               case 'unknown precipitation':
                    return 'rain.gif';
               case 'mist':
                    return 'mist.gif';
               case 'fog':
                    return 'fog.gif';
               case 'smoke':
                    return 'smoke.gif';
               case 'volcanic ash':
                    return 'smoke.gif';
               case 'sand':
                    return 'dust.gif';
               case 'haze':
                    return 'haze.gif';
               case 'spray':
                    return 'rain.gif';
               case 'widespread dust':
                    return 'dust.gif';
               case 'squall':
                    return 'flurries.gif';
               case 'sandstorm':
                    return 'dust.gif';
               case 'duststorm':
                    return 'dust.gif';
               case 'well developed dust':
                    return 'dust.gif';
               case 'sand whirls':
                    return 'dust.gif';
               case 'funnel cloud':
                    return 'flurries.gif';
               case 'tornado':
                    return 'storm.gif';
               case 'waterspout':
                    return 'storm.gif';
               case 'showers':
                    return 'storm.gif';
               case 'thunderstorm':
                    return 'thunderstorm.gif';
               default:
                    if (weather.indexOf("rain")) {
                         return 'rain.gif';
                    } else if (weather.indexOf("snow")) {
                         return 'snow.gif';
                    } else if (weather.indexOf("thunder")) {
                         return 'thunderstorm.gif';
                    } else if (weather.indexOf("dust")) {
                         return 'dust.gif';
                    } else {
                         return 'sunny.gif';
                    }
          }
     }
}

getConditions is simply a couple of large switch statements to retrieve the correct image. Once this is returned the image and the conditions details are set in the cookie. The last step is calling the setConditions function to display the details in the widget.

function setConditions(conditions, conditions_img, temp, humidity) {
     var country = $.cookie('loc_country');
     var region = $.cookie('loc_region');
     var city = $.cookie('loc_city');
     var loc_country_code = $.cookie('loc_country_code');
     if (loc_country_code == 'US') {
          temp = parseInt(temp) + 32;
          temp_type = "F";
     } else {
          temp_type = "C";
     }

     $("#weather_widget").append("");
     $("#weather_widget").append("

" + country + "

" + city + ", " + region + "

Temp: " + temp + "° " + temp_type + "

Humidity: " + humidity + "%

" + conditions.substr(0, 1).toUpperCase() + conditions.substr(1) + "

"); }

The rest is just a little bit of css and html.

Enjoy!
blog comments powered by Disqus