Using APIs with jQuery

Tuesday, February 16 2016


Working with external APIs is one of the cornerstones of a web developer's toolkit. I'm not going to go over the basics of HTTP and REST here; you should already have an understanding of how a "GET" request works. Instead, we're going to be focusing on:

  1. Getting the user's geolocation data (i.e., latitude and longitude)
  2. Using that data to interface with an API
  3. Using the JSON data to populate our application.

We're building a simple weather application using the Weather Underground API. You will have to create a free account and secure your own API key to get started.

The Markup

First, we lay down the HTML. I'll be using Bootstrap classes for the general styling. The IDs (found in the span tags) are the elements we will be manipulating with jQuery.

<div class="container text-center">
   <div class="well">
      <h1><span id="city"></span>, <span id="country"></span></h1>
      <div id="imgdiv">
         <img id="img" src=""/>
      </div>
      <h2><span id="temp"></span></h2> 
      <h3><span id="desc"></span></h3>
      <h5>Wind: <span id="wind"></span></h5>
   </div>
</div>

Geolocation

Now we're ready to move on to our JavaScript and grab our user's geolocation data. This can be done with the HTML5 Geolocation API. For more information about this API and how it works, click here. Keep in mind that the application must explicitly ask for the user's permission in order to get the data. There is no way around this without compromising privacy.

$(document).ready(function() {
   //define Geo object
   var Geo={};
   //check if browser supports geolocation
   if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success, error);
   } else {
      alert("Geolocation is not supported.");
   }
  //if there is an error
  function error() {
     alert("Unable to pinpoint your location.");
   }

In this snippet of code, we're checking to see if the user's browser supports geolocation. If it doesn't, we alert the user with a message. If it does, we'll create the getCurrentPosition function, which takes two parameters: what happens if the browser is able to get the geolocation data (success) and what happens in case it doesn't (error). This error function will be called if the user declines permission.

We also define a Geo object that we'll fill with our longitude and latitude. How do we do that? By using the success function below.

   //if location found
   function success (position) {
      Geo.lat = position.coords.latitude;
      Geo.lng = position.coords.longitude;

Now that we've grabbed our user's coordinates and stored both the latitude and longitude into the Geo object, we're ready for the fun part: interfacing with the Weather Underground API.

The Weather Underground API

Did you get your API key? Good, because this is where you're going to use it.

//use Weather Underground to get weather
   var apiKey = 'insert your key here';
   var currentWeather = "http://api.wunderground.com/api/"+ apiKey 
   + "/forecast/conditions/geolookup/q/" 
   + Geo.lat + "," + Geo.lng + ".json";

If you're wondering, the URL format comes directly from Weather Underground's documentation. We're using forecast, condtions, and geolookup, but you can use different data features depending on what information you want. Feel free to populate the url with your API key and your own latitude and longitude to see what the JSON looks like and get a feel for the raw data.

Now that we have the URL, we're going to use ajax to parse it.

$.ajax({
   url: currentWeather,
   dataType: "jsonp",
   success: function(data) {

The ajax method takes three parameters: (1) the url, which we defined already as currentWeather, (2) the dataType, which is jsonp (JSON with Padding, a technique of passing data between servers) and (3) what to do once ajax successfully gets the data. For more examples, you can review Weather Underground's code samples.

By looking at the JSON, I know what data I want: the city, the country, the temperature in Fahrenheit, an icon, the weather, and the wind. We'll pull that information from the JSON using bracket notation and store it in variables within function(data).

//variables from JSON
var localCity = data['location']['city'];
var localCountry = data['location']['country'];
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'];

Perfect! We have our data. With a little jQuery, we'll be able to easily populate our HTML spans.

   $('#city').html(localCity);
   $('#country').html(localCountry);
   $('#temp').html(temp + ' &#176;F');
   $('#img').attr('src', img);
   $('#desc').html(desc);
   $('#wind').html(wind);
   }
});
}
});

And that's our application! If you have any questions, please feel free to ask them in the comments.

Find the finished application on Codepen.

Back

Share "Using APIs with jQuery"