Using Google’s Weather API

Using Google’s Weather API

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on October 25, 2011

I thought it would be a nice little project to write a tutorial on how to build a basic but powerful weather application for either mobile devices or the desktop. The application takes a set of Google weather API feeds and makes some simple decisions based on the output. For example we can recommend the user takes an umbrella if rain or storms are forecast, or whether the temperature warrants the need for warm clothes. Basic but nonetheless useful information.

The Logic Code

Lets have a quick run through at what the project consists of. Firstly we use the simplexml_load_file() PHP function to get the xml data for the given location. We then check to see if the current weather condition is in the XML file. If it doesn’t exist then we can make the assumption that the API feed couldn’t determine the location, bear in mind this is very basic error checking and if the feed fails it will still return this error.

We now do some basic data checking to to see what extra data we can give the user. Firstly we check on line 14 to see if the current weather and forecast are different, if they are different we’ll display the forecast if not we show just the current weather.

Next on lines 21 and 28 we do a simple check to see if the temperature is higher or lower than 20 degrees and echo whether it’s likely to be hot or cold.

Finally on lines 35 we check to see if the current or future forecast contains any rain or storms so we can recommend the user takes an umbrella. This is done using some basic PHP regular expression.

	// load the XML feeds for the Google Weather API
	$xml = simplexml_load_file('http://www.google.com/ig/api?weather='.urlencode($_GET['location']));
	$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
	$forecast = $xml->xpath("/xml_api_reply/weather/forecast_conditions");

	// do a basic error check to see if we can get the current weather condition for the given location
	// if no return an error.
	if(!$current[0]->condition['data']){

		$error = 'Couldn\'t determine this location';

		}

	// is the current weather the same as the forecast? if not display the forecast
	if(strtolower($current[0]->condition['data'])!=strtolower($forecast[0]->condition['data'])){

	$outlook = 'but the forecast says '.strtolower($forecast[0]->condition['data']);	

		}

	// if the temp in degrees c is below 20 i.e. cold
	if($current[0]->temp_c['data']<=20){

	$coat = 'If you\'re going outside i\'d wrap up warm.';	

		}	

	// if the temp in degrees c is over 21 i.e. Warm / Hot
	if($current[0]->temp_c['data']>=21){

	$coat = 'You should be ok without warm clothes today.';	

		}		

	// check to see if there is rain or storms forecast
	if (preg_match("/\brain\b/i", $current[0]->condition['data']) ||
		preg_match("/\brain\b/i", $forecast[0]->condition['data']) ||
		preg_match("/\bstorm\b/i", $current[0]->condition['data']) ||
		preg_match("/\bstorm\b/i", $forecast[0]->condition['data'])
		){

		$umbrella = ' But <u>don\'t forget to take an umbrella</u>!';
		}

Displaying the data

<form action="" method="get">
<label for="location">Location</label>
<input type="text" class="location" name="location" value="<?php echo $_GET['location'];?>"/>
</form> 

<?php if(!empty($_GET['location'])){

	if($error){ echo '<div class="errors">'.$error.'</div>'; }else{

?>

<div class="weather_app">

<h1>Weather Summary for <?php echo $_GET['location'];?></h1>

<ul>
<li><?php echo '<img src="http://google.com'.$current[0]->icon['data'].'"/>'; ?> The weather in <?php echo $_GET['location'];?> is <strong><?php echo strtolower($current[0]->condition['data']).' '. $outlook;?></strong>. The temperature is currently <strong><?php echo $current[0]->temp_c['data']; ?>&deg;c (<?php echo $current[0]->temp_f['data']; ?>&deg;f)</strong>. <?php echo $coat;?> <?php echo $umbrella;?></li>
</ul>

</div>

<?php } } ?>

download


Recent shares

More tutorials from Papermashup
Comments
18 discussions around Using Google’s Weather API
  1. jeffey83 says:

    Thank for great post.
    You should change style type location , i think change to select + option tag html .

    Regards,

    http://alltour4you.com/

  2. Leszek says:

    Hi,
    Check this error for: http://papermashup.com/demos/google-weather-api/?location=g%C5%82og%C3%B3w

    You dont check Content-Type: text/xml; charset=$encoding_input

    For iso8859-2 it must do iconv($encoding_input, ‘utf-8′, $xml_from_google);

  3. sinun says:

    I tried to get the weather information from googles API with your script in another language. But with my knowledges i couldn’t get them. Could you give me some help to send additional information about language to the api?
    Thanks.

  4. mike says:

    Anyone know how to get the feed using classic asp? Thanks.

  5. Thanks for a nice tutorial, It’s a very simple and useful. I love the idea of the little friendly messages. Thanks a lot for sharing it.

    Regards,
    Razib
    http://www.donheymann.com/

  6. Randall says:

    This returns weather data for Paris France in XML format.
    http://www.google.com//ig/api?weather=paris
    This will also accept US zip codes.

    This link also has more information.
    http://www.instructables.com/id/Google-Weather-on-graphical-display-with-Arduino/

  7. sinun says:

    Did Google change the weather-api? Have a look at your demo site:
    “Warning: simplexml_load_file() [function.simplexml-load-file]: URL file-access is disabled in the server configuration in /nfs/c02/h13/mnt/40992/domains/papermashup.com/html/demos/google-weather-api/index.php on line 21″

    • Ashley says:

      @Sinun there was a problem with my PHP ini file, so it’s all fixed now. You need to make sure that your PHP ini file has ‘allow_url_include=1′

  8. Simon says:

    Great tutorial, would be great to be able to use custom icons though, how would you go about this?

  9. PitrusC says:

    Thanks for a great API tutorial, very simple and useful. Is it possible to replace Googles (ugly) weather icons with my own (beautiful) images ?? =)

  10. Really nice tutorial thanks

    I love the idea of the little friendly messages

  11. Logo Blog says:

    This is Great apps! i have’nt use it before! but i found it very interesting :)
    thanks

  12. Rilwis says:

    Nice tutorial. It would be better if I could find a link to Google Weather API and a returned format. Anyway, the code looks clean.

  13. Stanko says:

    I made something similar long time ago :)
    Take a look at the demo, I’m to lazy to write some docs and to release it. But I hope I will do it soon…
    http://sale.mfhinc.net/demos/weather-widget/
    Cheers!

  14. Sahba says:

    Can this google weather xml data be used for a commercial weather website? Could I just use the data to make my own weather website?

  15. sinun says:

    Thank you for this interesting article. – Another idea: A display of the solar UV index. Thank you for your great work.

  16. Steve Strutt says:

    It’s also worth noting that the Google Weather API is stable (there aren’t many changes) even though it’s undocumented. I’ve been using it for http://instantwx.com for more than a year without touching the code.

  17. Serge says:

    Thanks for another great post Ashley!

    Google API + custom messages = cool application
    I would definitely use it in my future projects.

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>

Looking for a registry cleaner to speed up your PC and show a full diagnostics?
Faster surfing with Dish Network High Speed Internet

Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in touch.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com you can find details here Or use the contact link below for further advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.