Tags : JavaScript Intro



Working with API's

We will use jQuery's $.get function to interact with an API.

index.html

<!DOCTYPE html>
<html>
  <head>
    <script src="scripts/jquery-1.11.3.js"></script>
    <script src="scripts/myscript.js"></script>
  </head>
  <body>
    <input type="text" id="city-weather" placeholder="city">
    <button type="button" id="look-up-weather">Weather Please</button>

    <table class="cities">
      <thead>
        <tr>
          <th>City</th>
          <th>Temp Low</th>
          <th>Temp High</th>
          <th>Wind speed</th>
        </tr>
      </thead>
      <tbody class="results">
      </tbody>    
    </table>
    <span id="city-result"></span>
  </body>
</html>

myscript.js

$(document).ready(function(){
    var apiKey = "your own api key";
    var apiUrl = "http://api.openweathermap.org/data/2.5/weather?q=";

    $("button#look-up-weather").on("click", function(){
      var city = $("input#city-weather").val();
      $.get(apiUrl + city + "&APPID=" + apiKey, function(data){
        $("tbody.results").append("<tr><td>" + city + "</td><td>" + data.main.temp_min + "</td><td>" + data.main.temp_max + "</td><td>" + data.wind.speed + "</td></tr>");
      })
    })  
  })

Try the following:

  • Read the API documentation at openweathermap.org
  • Try to see if you can get the temperature working with Celsius.
  • Try to get a 5 day forcast for a city and display it to the user.
  • Try to get a 16 day forcast for a city and display it to the user.
  • Add animations of sunny, cloudy, rain or snow and apply them to the response.