Build a Geolocation Weather App



Tweet

Getting Started

This weather app tutorial will use HTML geolocation to auto-detect the user’s latitude and longitude and then will use those coordinates to determine the weather using the Dark Sky API. Before we start, you must sign up for your API key over at Dark Sky. Once you sign up and reach to your console, take note of your API key. Just for your information, this API is free for up to 1,000 requests/day.

Now that we have our API key, we can create our files:

As you probably saw in the preview above, we’re going to be displaying the current temperature, a short summary, and the coordinates based on the user’s location. That’s why we’ll need three divs in addition to adding the jQuery CDN (for the API request) and linking our style.css and app.js files.

  <html>
     <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css" />
        <title> Weather </title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
     </head>

     <body>
        <h1><div id="temp"></div><div id="minutely"></div></h1>
        <h2><div id="location"></div></h2>
     </body>
     <script src="app.js"></script>
  </html>

The weather() function

Our JS file will be centered around HTML’s geolocation.

This is what we need to incorporate:


  function weather() {

    var location = document.getElementById("location");
    var apiKey = 'INSERT API KEY';
    var url = 'https://api.forecast.io/forecast/';

    navigator.geolocation.getCurrentPosition(success, error);

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

      location.innerHTML = 'Latitude is ' + latitude + '° Longitude is ' + longitude + '°';

       $.getJSON(url + apiKey + "/" + latitude + "," + longitude + "?callback=?", function(data) {
        $('#temp').html(data.currently.temperature + '° F');
        $('#minutely').html(data.minutely.summary);
      });
    }

    function error() {
      location.innerHTML = "Unable to retrieve your location";
    }

    location.innerHTML = "Locating...";
  }

  weather();


There you have it! We now have a functional weather app :)

Some styling

Here’s my take on some basic centering and font changes in CSS. Feel free to style the page to your liking.

  html {
    font-family: "Avenir Next", Helevetica, sans-serif;
    text-align: center;
  }

  body {
    margin: 0 auto;
  }

  h1, h2 {
    font-weight: 300;
  }

I encourage you to try to explore more with the world of APIs. You can build a Quote Generator that uses a quote API, or you could even further advance this project by adding more weather details from the Dark Sky API!