How to load weather data in JavaScript using jQuery, d3 or node.js

Many applications need reliable weather forecast data or historical weather data that can be directly accessed from JavaScript code. They may be as simple as a weather forecast widget, a sophisticated historical weather data dashboard built using a JavaScript library such as jQuery, d3 or even a server side JavaScript application using node.js.

All of these applications need to be built on a solid weather API such as the Visual Crossing Weather API. In this article we show the basics of retrieving weather data using JavaScript.

Step 1 – set up a Weather API account

You can easily sign up for a free account on our Weather Data Services page. For more more information see How to sign up for a weather data services account.

Step 2 – create a Weather API request

The weather API includes many features and options. In this example we’re going to use a simple request so we can focus on the JavaScript handling of the request and response. As an example, we will use the following request to grab the weather forecast. If you would like to see more examples of the Weather API, take a look at some common weather API requests. See the Weather API documentation for full documentation and API reference.

Here is the request to retrieve the weather forecast for a single location:

  https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast? aggregateHours=24&locationMode=single&contentType=json&unitGroup=us&key=YOUR_API_KEY&locations=New York City,NY

Note that you will need to replace ‘YOUR_API_KEY’ with your actual API key that you obtained in step one above.

Step 2 – create a Javascript script to retrieve weather data

We are now ready to write some JavaScript code to retrieve weather data. Depending on your favoured JavaScript library, such as jQuery, d3 or maybe no library at all, the exact code will vary so we will describe several commons examples.

In all cases, we will submit the example API request discussed above. Each request will ask for the weather forecast in JSON format (see the parsing the response section below). Each handler will perform some basic error checking before passing the data to the next section to display some of the results.

Sample 1 – XMLHttpRequest request

In our first example, we use the browser XMLHttpRequest request object.

     function requestXMLHttpRequest() {
        var xhr = new XMLHttpRequest();
        xhr.responseType = "json"; //1
        xhr.open('GET', uri);        
        xhr.send();
        xhr.onload = function() {
            if (xhr.status != 200) { //2
                console.log("XMLHttpRequest error: "+xhr.status);
                return;
            }
            processWeatherData(xhr.response); //3
        };
        xhr.onerror = function() { //4
            console.log("XMLHttpRequest Request failed");
        };
    } 

The code is quite straightforward. We indicate to the XMLHttpRequest that we are expecting JSON output (line 1). This will mean the xhr.response is automatically populated as JSON.

We then request the data from the weather API uri (the ‘uri’ variable is populated with our weather API request).

We perform two pieces of error handling – the onerror function of the XMLHttpRequest instance (line 4). We also check the HTTP response status (line 2) to ensure it is marked as 200.

Finally we pass the data to the processWeatherData method (which we will discuss below).

Sample 2 – jQuery request

In our second example, we use the jQuery library. Again we request the weather response via a GET request and pass the JSON response (which has already been parsed) to the processWeatherData method. Note that there’s no requirement to use GET, you can use POST instead if you prefer.

   function requestjQuery() {
        $.get(uri) .done(function(rawResponse) {
            processWeatherData(rawResponse);
        })
        .fail(function() {
            console.log("jQuery Request failed");
        });
    } 

Sample 3 – d3 request

In our third sample, we use d3. d3 “is a JavaScript library for manipulating documents based on data”. If you are already using d3 in your existing application, you can use it to request the weather data directly within the library. The code works very similarly to the jQuery code:

     function requestd3() {
        d3.json(uri, function(error, rawResponse ) {
            if (error) {
                console.log("d3 error: "+xhr.status);
                return;
            }
            processWeatherData(rawResponse);
        });
    } 

Again by using the d3.json method we have indicated to d3 that we are expecting a JSON output. Assuming that no error is flagged, we can pass the result directly to our processWeatherData method.

Note that we could have requested the data in CSV format rather than JSON. JSON is easy to use as it is natively parsed by the browser. However, if you are using d3 however then it would be easy to use the CSV instead since d3 can parse CSV directly.

Step 3 – process the response

In our previous step, we have successfully retrieved weather data from our weather API request. We can now use the data. In this simple case, we are going to output some of the information to the JavaScript console.

function processWeatherData(response) {
  if (!response) { //1
    console.log("Empty response");
    return;
  }
  if (response.errorCode>0) {  //2
    console.log("Error detected. errorCode="+
               response.errorCode+", 
               message="+response.message);
    return;
  }
  var location=response.location;
  var values=response.location.values;
  console.log("Location: "+location.address);
  for (var i=0;i<values.length;i++) {
    console.log(values[i].datetimeStr+": maxt="+values[i].maxt+", 
         mint="+values[i].mint);
  }
}

After checking that the data exists and that no errors have occurred (lines 1 and 2), we request the location instance. this contains overall information about the location and also the weather data values themselves.

We print out the location address and then loop through the values, printing the date time, maximum and minimum temperatures.

For a full description of the JSON, see our JSON documentation.

Closing remarks

As you can see, it only takes a few lines of code to include weather data into your JavaScript application. If you would like the full source to our example above, please download it from our repository.

Questions or comments, please ask below or contact support at support@visualcrossing.com.

Leave a Reply

Your email address will not be published. Required fields are marked *