Grow your CSS skills. Land your dream job.

Live Weather Display Using CSS, jQuery and PHP

Published by Guest Author

The following is a guest post by Darren Jamieson, the technical director for Engage Web, an online marketing firm in the UK. We fiddled around with this back in 2008, but I thought it might be nice to share an updated technique and Darren obliged with his work. This takes the idea to another level by combining the sun and moon and time of day in addition to the weather.

In 2006 I had an idea which involved displaying a live weather feed on a company’s website, using the Yahoo Weather API as the source. At the time however, the only way to do this effectively was by using Flash, and this was something the company was unwilling to do due to the development time involved.

Six years later, as the technical director of my own business, Engage Web, I revisited this idea for our newly rebranded company – and moved it on a couple of stages. In 2012, Flash was no longer necessary, as everything it could do in 2006 could now be done with CSS3 Keyframes.

We set out with ambitious plans to have our website feature the live weather conditions using the geo location from anyone who looked at it. We wanted the time of day to be reflected depending on where they were based in the world, so somebody looking at the website in London, England would see a different style to someone looking at the website at the exact same time in San Diego, California. The goal was that people could see what the weather was like outside their window by looking at our website.

Here are just a few examples of the final state the header of the site can look like at any given time:

example-day
Daytime

example-heavy-rain
Heavy Rain

example-heavy-snow
Heavy Snow

example-light-clouds
Light Clouds

example-mild-rain-nighttime
Mild Rain at Night

example-mild-rain
Mild Rain

example-nighttime
Nighttime

Unfortunately, we ran into some immediate snags of a technical nature caused by the old nemesis of the web developer, Internet Explorer. IE wasn’t able to handle geolocation, so getting an accurate approximation of a person’s location from their browser wasn’t possible. Instead we had to use an IP lookup API to get the location of the user, which is only accurate to the user’s nearest capital city (or large city). For this we have used ipinfodb.com. Based on the IP Address entered into this site, it returns the Country, State/Province and City/Town of the user. We only needed the Country and the Town/City, which is then fed into Yahoo’s Weather API, giving back live weather data for the area.

If no data is fed back from ipinfodb.com (for example if the website ever went down, or IP data couldn’t be retrieved from the user) the location is defaulted to London, England.

Both the Yahoo Weather API and ipinfodb.com feed back longitude and latitude, which is then used to calculate the sunset and sunrise times, which in turn trigger the sunrise and sunset on the website.

The final egg in the pudding is the moon phase, which was the most complicated of all the calculations, even though it required just the date as a variable.

Whether the Weather is Rain or Shine

Let’s start with the weather. Yahoo returns the weather information in the form of a number, currently between 0-47, with an error number 3200 for no information. Each one of those numbers represents a different weather type.

0  	tornado
1 	tropical storm
2 	hurricane
3 	severe thunderstorms
4 	thunderstorms
5 	mixed rain and snow
6 	mixed rain and sleet
7 	mixed snow and sleet
8 	freezing drizzle
9 	drizzle
10 	freezing rain
11 	showers
12 	showers
13 	snow flurries
14 	light snow showers
15 	blowing snow
16 	snow
17 	hail
18 	sleet
19 	dust
20 	foggy
21 	haze
22 	smoky
23 	blustery
24 	windy
25 	cold
26 	cloudy
27 	mostly cloudy (night)
28 	mostly cloudy (day)
29 	partly cloudy (night)
30 	partly cloudy (day)
31 	clear (night)
32 	sunny
33 	fair (night)
34 	fair (day)
35 	mixed rain and hail
36 	hot
37 	isolated thunderstorms
38 	scattered thunderstorms
39 	scattered thunderstorms
40 	scattered showers
41 	heavy snow
42 	scattered snow showers
43 	heavy snow
44 	partly cloudy
45 	thundershowers
46 	snow showers
47 	isolated thundershowers

We then split the weather types into four numbers. The first number controls the clouds, how light or dark they are and how heavy they are. The second number controls the rain. There are several degrees of rain on the website, ranging from light showers to heavy downpours. The third number controls effects, such as lightning or snow, and the fourth number is for incidental effects, such as dust or fog.

$weatherarray[39]=array('scattered thunderstorms',3,2,5,2);
$weatherarray[40]=array('scattered showers',3,2,0,2);
$weatherarray[41]=array('heavy snow',1,0,3,0);

One of the more common effects we see in the UK is rain (we get a lot of rain) so here is how the rain effect is done on our site. The below animated rain gif is displayed with a suitable opacity, depending on how heavy the rain is reported as being in the weather API from Yahoo. Our previous code takes the information from Yahoo and assigns variables for the rain strength, and these variables control the opacity of the animated rain gif in the below code.


animated-rain
switch ( $effect1) {
    case 0:
        $weathercode.= '
             jQuery(\'#rain\').css("opacity", "0.0"); 
       ';
        break;    
     case 1:
        $weathercode.= '
             jQuery(\'#rain\').css("opacity", "0.10"); 
       ';
        break;     
      case 2:
        $weathercode.= '
             jQuery(\'#rain\').css("opacity", "0.30"); 
       ';
        break;
      case 3:
        $weathercode.= '
             jQuery(\'#rain\').css("opacity", "0.50"); 
       ';
        break; 
}

Full Moon, Half Moon, Total Eclipse

The most difficult part of the whole process was the moon phase. To do this we created a large image displaying 10 different variations of moon phase. The CSS then decides how to display the correct image based on the data fed back from a PHP script (the calculations for which are, quite literally, astronomical).

background-position: <?php echo $moonbgimagepos; ?>px 0;


mooncycle

The script to calculate the moon phase was derived from code which can be found here.

300 seconds to Sundown

The pièce de résistance of the project is the sunset and sunrise effect, which happens depending on the actual sunset and sunrise times at the location of the person looking at the website. Using the longitude and latitude we have previously mentioned, the sundown and sunrise time (depending on whether is currently day or night) is extrapolated, converted to a unix timestamp, and stored as a variable.

The current time is also converted to a unix timestamp, and the difference between the sunset or sunrise time and the current time is applied as a timeout to a jQuery function which handles the transitions between day and night, and vice versa.

The following jQuery controls the transition between three stages. For sunset the ‘daytime’ background is faded out, and is replaced by an orangey glow background (used for sundown and sun-up) which itself is then faded out into a night time background. While this is happening, the sun itself begins its decent from the top of the page to the bottom, which takes 300 seconds to complete.

jQuery('#daytime').fadeOut(200000, 'linear', function() {

  jQuery('#sill').fadeOut(100000, 'linear', function() {});

  jQuery('#sunset').fadeOut(100000, 'linear', function() {});
});   

While this is occurring, any relevant weather effects are also overlaid on the screen, such as rain, snow, lightening and cloud movement. As an added effect, the skyline also transitions from a day theme to a night theme to show the buildings descent into darkness, and the city lights come on.

Working Day and Night

As an added effect, the additional style elements of the website, such as colouring effects, are changed depending on whether the is time is day or night. This is done by using a PHP file as CSS once the variables have been established.

<link rel="stylesheet" type="text/css" href="/css/styleweather.php" />

If you happen to catch the website while the sun is setting or rising however, you see the skyline and site theme change as the day transitions to night, and vice versa. The following code controls this using jQuery:

jQuery('#backmask').animate( {
    color: '#fff',
    backgroundColor: '#48508b'
    },300000, 'linear' );
jQuery('#menu-top-menu li,#blogmenu,#searchbox, #times').animate( {
    color: '#fff',
    backgroundColor: '#48508b'
    },300000, 'linear' );
jQuery('#Phone').animate( {
    color: '#fff',
    backgroundColor: '#48508b',
    boxShadow: '0 -10px 10px 4px #2A3160 inset'
    },300000, 'linear' );

Testing, Testing, 123

When building something which is triggered by the sunset and sunrise times derived from the longitude and latitude of the user, testing the effect was a mission in itself. This required working out where in the world the sun was about to rise, and then connecting to the website via a proxy server in that country to check the timings. We learned a lot about geography, time zones and sunrise times working on this project!

Here's a screenshot of the website with the effect working:

final-screenshot

Credit to designer/developer Steven Morris for the design work on this project.

Comments

  1. Rodrigo Quintas
    Permalink to comment#

    Awesome work Darren.
    Loved the creative thinking behind this project. And the way it works… Great!
    It’s people like you (and you, Chris, of course ;) )that keeps me chasing a new career in this vast world of web design/frontend dev.

    Thanks!

  2. Not long ago I daydreamed of a project like this, minus the motivation to actually do it. something like this could help support a project in artificial intelligence, – – the current weather could impact what kind of mood your online a.i. creation is in.

    current events could also dictate what kind of mood an online A.I. bot would be in. there could be numerous ways to put an index on how good or bad something on the news is… but for the a.i. to come up with an opinion on a current event sounds very tricky.

  3. Good creativity by Darren.

  4. ahmed
    Permalink to comment#

    hai can you help me to get in css area.i have some problem when i go for css designing
    i cant make it .if i need any practice ? guide me to learn thing css

    thank you

  5. Permalink to comment#

    It is a best designer and developer coordination .

  6. An out of this world creativity. Great job Darren, it’s sad that even in 2012, IE sucks!

  7. Cactus
    Permalink to comment#

    Nice stuff! I did the same thing with a page that never got launched. I took the location of the user, created a google map, centering in on the users location, then checked with google weather (this probably doesn’t work anymore) and then added a layer (with opacity set to some nifty value) with image of the weather (rain, snow, clouds and so on). If I get the time I could probably post the instructions somewhere as well :) . Great work!

  8. Thanks for the great comments guys. I need to email Chris today and to have our designer’s name attached to this, as all the hard work was his. The guy who coded this insane project is Steven Morris – he deserves the plaudits.

  9. Permalink to comment#

    Wow! This is amazing :D

  10. Louis
    Permalink to comment#

    This exactly what I need to implement for a boating website. Inspired!

  11. Mr. Man
    Permalink to comment#

    Is there a reason that you’re using jQuery instead of $?

  12. Excellent Article! Hey Chris – don’t you think, it would be nice if we have the ‘tweet’ button & the ‘like’ button for articles?

  13. A disgruntled developer
    Permalink to comment#

    Nice concept but the execution is shoddy at best. You can see blue pixels from where the building images were not cut out correctly, no anti-aliasing on said buildings and low quality images being used for everything. The rest of the site is a similar mess, to be fair. Ugly silver gradients from a decade ago on the menu buttons, footer which looks out of place (seriously, where’s the transition?), share buttons in the friggin heading. Do yourselves a favour and fire your designer.

    Telling you what nobody else has the heart to, since 1985.

    • not disgruntled
      Permalink to comment#

      I would have to agree. Site leaves much to the imagination. Although they are a social media company, so to me the share buttons on the top kind of makes sense. And just because the logo is in that purple, doesn’t mean the rest of the site needs to be. That is all

  14. Love it, This is brilliant

  15. Les
    Permalink to comment#

    Code ninja. Brilliant!

  16. Permalink to comment#

    What an insane post. CSS-Tricks is always filled to the brim with cool stuff, but this sets the standard.

  17. Honesty
    Permalink to comment#

    Conceptually, brilliant. The execution is questionable.

  18. great IDEA

  19. Madara Uchiha
    Permalink to comment#

    You have a typo at the first sentence, I’m pretty sure you’re not the technical directory :)

  20. Permalink to comment#

    We are not worthy! Great stuff.

  21. Permalink to comment#

    Kudos to Steven Morris.

    Love the moon phases approach as well. I really enjoyed the read and the “sticktoitiveness” required for such an undertaking.

    Very nice job and thank you for sharing!

  22. When I see a post like this I realize that I am still a grasshopper in regards to all this…amazing post…Thank you for sharing your knowledge…

  23. Mitch
    Permalink to comment#

    Dunstan did this a few years ago.

  24. Andy
    Permalink to comment#

    can any one tell me, how to download this awesome stufff?

  25. Great post Darren, love the concept.

  26. Permalink to comment#

    I started a similar project a couple of weeks ago, the only difference is that the weather is displayed with a cartoony webgl 3d scene using threejs. I’m having a big problem though. On the yahoo weather API website, they say:
    “For the Weather RSS feed there are two parameters:
    w for WOEID.
    u for degrees units (Fahrenheit or Celsius).
    The WOEID parameter w is required. Use this parameter to indicate the location for the weather forecast as a WOEID.”
    How can you dinamically find the WOEID for the client’s location?
    Thanks
    J

    • Steven
      Permalink to comment#

      You can query the Yahoo API with place names, long and lat and other values and it will return a WOEID for you.
      Will require a Yahoo API key but the query address is http://where.yahooapis.com/geocode then add your params

      It will even take plain text like “london” or “Glasgow”

      Hope that helps

    • Jonas
      Permalink to comment#

      Exactly what I needed, thank you very much!

      Jonas

  27. Permalink to comment#

    Will it auto select the visitor location or It only displays manually selected cites.

    Also whats the plugin impact on resource usage?

    Regards

  28. Hi Chris (and Darren) – great article and love the way you push CSS to it’s limits, I now have one additional challenge for you… for which I have no idea if it can be achieved.

    If it’s raining – it’s rather sad and the weather graphic produced would be dark, rainy and uninspiring… so instead, could it be made possible to look ahead at the forecast and tell us when it would next by Sunny (good weather). Could you get the php code to look up the Yahoo API and find the next sunny day for that IP.

    Then you could always show a sunny image and perhaps a message ‘don’t worry – it will next be sunny in your location on Tuesday…etc…’

    Might be more user friendly, than just telling people what their weather it like right now.

  29. Great article, Darren! This is a really creative technique you’ve applied here.

  30. Permalink to comment#

    Very nice tips, thanks for sharing Darren!

  31. Permalink to comment#

    Love this very nice to share the knowhow :) 10x

  32. Permalink to comment#

    Great article! thank so much!

  33. gid
    Permalink to comment#

    WOW, awesome! stuff

  34. This is absolutly great work. Even though this is not simple – this is nothing but fantastic. This is something to write home about. Great work!!

  35. In 2007 I did this for NYC. The weather, the time of day, the phase of the moon, and the colors of the Empire State Building all matched the real world. Sometimes the view out my window was eerily similar, sometimes not so much. But once in 2009 it Thundersnowed in NYC and I was so glad I built that in even if it was only visible for 1 or 2 glorious hours.

    http://newyorkontap.com/newyorkskyline.asp

This comment thread is closed. If you have important information to share, you can always contact me.

*May or may not contain any actual "CSS" or "Tricks".