Open Weather Map API – Retrieving Weather Info

Today, we are going to make a small project connecting to a Open Weather API, retrieve its information depending in the state and country, show it to the user, and in the next post we will add a 5-day forecast to our project. Here is the link to their official site, so you can check their documentation, which is very important to read since it if ask ourselves how to make “X” thing.

Let’s get started

I used Netbeans to create the project, however, you can use any text editor for this, even with notepad. The technologies that will be used in this project are:

  • HTML
  • CSS
  • Javascript

First, let’s create a new project in Netbeans or in your favorite text editor as shown in the following image:

Create Project

Note: This is my project structure, you can do something similar to mine.

Project Structure

Now, let’s create a new javascript file, we will call it “mainWeather”. Remember to add Jquery. Now that you have created a JS file, let’s add it:

<!DOCTYPE html>
<html>
    <head>
        <title>Open Weather API</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript" src="resources/js/jquery.js">
        <script type="text/javascript" src="resources/js/mainWeather.js"></script>
    </body>
</html>

After doing so, let’s add one input for the city and another one for the country as well as a button to submit the information.

<!DOCTYPE html>
<html>
    <head>
        <title>Open Weather API</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
          <div id="UserArea">
            <div id="stateWrapper">
                <input type="text" id="cityInput" placeholder="Enter a State"/>
            </div>
            <br/>
            <div id="countryWrapper">
                 <input type="text" id="countryInput" placeholder="Enter a Country"/>
            </div>
            <br/>
            <div id="buttonArea">
                <input type="submit" id="submitWeather"/>
            </div>
        </div>
        <!- USED TO SHOW RESULT -->
        <div id="WeatherWrapper">
        </div>
        <script type="text/javascript" src="resources/js/mainWeather.js">
        <script type="text/javascript" src="resources/js/jquery.js"></script>
    </body>
</html>

Now we have prepared the front end, we are moving to the javascript side, here is where the fun starts! You will notice that I used an object literal, basically, I am just storing all the functions I am going to use in a variable and later on calling those variables using something similar to: “mainWeather.init();”. In my opinion, this makes the code more readable and easier to follow up.

First things first, let’s understand how the api works; to start using it, you will need to send the country and the city using this url “http://api.openweathermap.org/data/2.5/weather?q=state,country”, where you will change the “state” and “country” to what you are typing; we are going to use jquery ajax to send the request and received a response. The response should be an object that will contain all the data we need, it is simple, right?

In the code below, you will see a function called “getWeather” with only an ajax function, this is the part I was mentioning before, you will need to create an ajax request with the url I wrote a couple of lines above and set the type as “GET” as well as the dataType to JSONP, for those who doesn’t know what JSONP is for: “JSONP was created as a workaround to the cross domain problem. The cross domain problem refers to the fact that Ajax code run from website A can’t access data from website B.” You can read more in this link.

I created a function that will build the weather widget for me, receiving as parameter the object from the response. After we have the code ready, let’s add everything to the success method in the ajax request. I added an empty div in the index html file so I can print the results, named “WeatherWrapper”. It is recommended that you empty the div before appending all the information, you wouldn’t like to have different results mixed up when you are looking for a specific one, right? For example, we are looking for “Houston,Texas”, but we have already looked for 3 or more cities, they will just accumulate until you leave the page. Okay, so now we will be appending everything to the wrapper by sending the return data to the createWeatherWidg.

var mainWeather = {
      init : function(){
          $("#submitWeather").click(function () {
                    return mainJS.getWeather();
            }
        });
      },

    getWeather: function () {
        $.ajax({
            url: 'http://api.openweathermap.org/data/2.5/weather?q=' + $("#cityInput").val() + "," + $("#countryInput").val(),
            type: 'GET',
            dataType: 'jsonp',
            success: function (data) {
                var wrapper = $("#WeatherWrapper");
                wrapper.empty();
                wrapper.append("<div class='city'> <p>Place: " + data.name + ", " + data.sys.country + "</p></div>");
                wrapper.append(mainWeather.createWeatherWidg(data));
            },
            error: function () {
                alert('Failed!');
            }

        });
    },

      //Prints result from the weatherapi, receiving as param an object
       createWeatherWidg: function (data) {
        return "<div class='pressure'> <p>Temperature: " + (data.main.temp - 273.15).toFixed(2) + " C</p></div>"+
                "<div class='description'> <p>Title: " + data.weather[0].main + "</p></div>" +
                "<div class='description'> <p>Description: " + data.weather[0].description + "</p></div>" +
                "<div class='wind'> <p>Wind Speed: " + data.wind.speed + "</p></div>" +
                "<div class='humidity'> <p>Humidity: " + data.main.humidity + "%</p></div>" +
                "<div class='pressure'> <p>Pressure: " + data.main.pressure + " hpa</p></div>";
    }
}

Things to check: data contains various objects (data.weather, data.main, data.wind), which contains other information if you would like to add. The temperature you will get is in Kelvin, let’s subtract 273.15 to get the temperature in Celsius.

We are almost done! Let’s just add this function to the onclick event of the button we created before. You can see the init method to check how I did it, and we call the init method either in the same JS file or in the HTML inside the $(document).ready() function:


$(document).ready(function(){
mainWeather.init();
});

Now you are ready to run it! This will be it, for better understanding, you can see what’s being returned from the ajax call and mess with it, you could find other variables that you would like to show. If you would like to improve this project, you can make it prettier, make it a widget similar to this image. I will make a new post that will show how to use this and a 5-day forecast, let me know if you have any questions or comments.

By the way, here are some of the results I received:

Ottawa, CA LA, US

Update: OpenWeather has updated the way you need to call their API, you now require an APP ID in order to send request. We will just need to add ‘&APPID=[XXXXYOURAPPIDHEREXXXX]’ to the URL we had before in the ajax call.

Demo: