How to build a weather app with HTML5’s Geolocation API

The most amazing part of all the technologies that came with HTML5 is how easily they can be used to create little apps that make our lives a lot easier. It’s surprisingly simple to combine them to create something practical and simple.

Today we will be using geolocation and the Weather Underground API to create a simple Weather App that will determine where you are and tell you the current weather for your location.

To work with the Weather Underground API you will need an API key but don’t worry because it’s free, although it has a limit of 500 calls a day.

How does Geolocation work?

Geolocation is a technology that allows websites to be location-aware of where the user stands using their current IP address, in a mobile app it can also use the built-in GPS for a more accurate reading.

The specification of this API states that to maintain the user’s privacy the browser must show a dialog that the user must accept in order for the Geolocation to work and if declined the code won’t run.

The markup

The first thing we will need to do before moving into the JavaScript is create the markup. It looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Weather APP</title>
<link rel="stylesheet" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="forecast">
<h1>Weather at <span id="location"> </span></h1>
<div id="imgdiv">
<img id="img" src=""/>
</div>
<p>It is currently <span id="temp"> </span>ªF with <span id="desc"> </span></p>
<p>Wind: <span id="wind"></span></p>
</div>
</body>
</html>

Just by looking at the markup you can see where all the information we are getting is going and we are ready to start the JavaScript.

Getting started with JavaScript

The first thing we need to is check if the user’s browser supports geolocation, show an error message if it does not, and create the getCurrentPosition function if the browser does support it. For that we create an if statement checking for navigator.geolocation and we will also create a Geo object that we will fill later with our longitude and latitude coordinates:

var Geo={};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success,error);
}
else {
alert('Geolocation is not supported');
}

As you can see the getCurrentPosition functions takes two parameters, one is for what we want to happen if the browser is able to get your location and the second one is where you determine what you want to do in case it doesn’t, for the second one we will just create a function that alerts the error:

function error() {
alert("That's weird! We couldn't find you!");
}

Getting the basic error handling out of the way we are ready to dive into the building of this little app and now we will create the success function and the first thing we will do is get the current latitude and longitude to fill the Geo object we created:

function success(position) {
      Geo.lat = position.coords.latitude;
      Geo.lng = position.coords.longitude;

Now that we got the coordinates we can use them in the Weather Underground API, and in here we will need three things:

  • The API Key
  • The Latitude
  • The Longitude

Since we got the two bottom items, and I am assuming you already have your API key, we can insert them into the url like so:

var key = ‘insertyourkeyhere’;
var Weather = "http://api.wunderground.com/api/”+ key +”/forecast/geolookup/conditions/q/" + Geo.lat + "," + Geo.lng + ".json";

Now that we got the url for the API and we need to get the json file and parse it using jQuery and for that we will use the ajax method that takes 3 parameters: the URL we wish to parse (we already have that stored in the weather variable), the data type, and also we have to tell jQuery what to do if it succeeds in getting the json:

$.ajax({
url : Weather,
dataType : "jsonp",
success : function(data) {
// get all the information
}
});

The first thing you may find weird in here is the fact that in the data type we didn’t use json but rather jsonp, this is a technique of passing data between servers using JSON, it’s not a different language.

In this success function we will get the information we need and in the example I will be getting:

  • The location of the user (city name)
  • The temperature
  • The text description of the weather
  • The wind information
  • And the image that represents the weather at the location

We know that json uses objects and if you look at an example of the Weather Underground API we’ll see that except for the city name all this information is in the current_observation object so it will be quite easy getting all the properties we want and assigning them to variables.

var location =data['location']['city'];
var temp = data['current_observation']['temp_f'];
var img = data['current_observation']['icon_url'];
var desc = data['current_observation']['weather'];
var wind = data['current_observation']['wind_string'];

As you can see, all we did was access the data that we fetch from json, search the object we wanted and get the property inside it. If you are familiar with reading arrays in PHP this should all sound very familiar to you.

Just like that, we have everything we need to start filling our page with the information, and using the jQuery html and attr method this will be quite simple and painless:

//setting the spans to the correct parameters
$('#location').html(location);
$('#temp').html(temp);
$('#desc').html(desc);
$('#wind').html(wind);
//filling the image src attribute with the image url
$('#img').attr('src', img);

jQuery helps a lot in this situation and all we need was a line for each element we had in the page.

Conclusion

I hope that from this tutorial you got a better understanding of how Geolocation works and how to apply it to real life situations. There a million uses for Geolocation, if you find an interesting one, let me know in the comments!

Sara Vieira is a freelance Web Designer and Developer with a passion for HTML5/CSS3 and jQuery. You can follow her on twitter or check out her website. More articles by Sara Vieira
  • rosshi

    hi, interesting, however why is it that new generation web designers don’t make their sites accessible? The text above for instance cannot be highlighted and therefore cannot be read by my screen reader, the web and its content should be accessible to all, please try to keep accessibility in mind… TY… 🙂

    Culata
    A→T→B
    rosshi

  • rosshi

    oops, my apologies The text does highlight. But the highlight colour is almost invisible to my sight…

    Culata
    A→T→B
    rosshi

  • Bipratip

    It was great but I suggest that you should zip the file and put a download link so that viewers could easily download it and study its content.

    • Wesley Hopkins

      i too would like this as i was confused. Does this all go into the html? or do you create a seperate .js file???

  • hemant kushwah

    Hello There, Can U Please provide the code in Zip format. The upper code is not working. I think I am not using it correct way.

Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress