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/timeline/New%20York%20City%2CNY?unitGroup=us&key=YOUR_API_KEY&contentType=json
Note that you will need to replace ‘YOUR_API_KEY’ with your actual API key that you obtained in step one above.
Step 3 – create a JavaScript script to retrieve weather data
We are now ready to write some JavaScript code to retrieve weather data. Depending on your favored JavaScript library, such as the fetch API, 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 – Fetch API request
Our first example uses the Fetch API to retrieve the weather API result. While not supported by older browsers, all major browsers have supported the Fetch API for more than five years. If you are not needing to support older browsers, and don’t need to directly populate a library such as d3, then the fetch is likely the best choice.
fetch("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY?unitGroup=us&key=YOUR_API_KEY&contentType=json", { "method": "GET", "headers": { } }) .then(response => { console.log(response); }) .catch(err => { console.error(err); });
The Fetch API sample can be made directly within our API code builder utility within the Weather Data Services Query Page. Note that this sample does not process the text result or error. To do that, another promise-based call is necessary:
fetch("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY?unitGroup=us&key=YOUR_API_KEY&contentType=json", { method: 'GET', headers: { }, }).then(response => { if (!response.ok) { throw response; //check the http response code and if isn't ok then throw the response as an error } return response.json(); //parse the result as JSON }).then(response => { //response now contains parsed JSON ready for use processWeatherData(response); }).catch((errorResponse) => { if (errorResponse.text) { //additional error information errorResponse.text().then( errorMessage => { //errorMessage now returns the response body which includes the full error message }) } else { //no additional error information } });
In this example, we use the Fetch API to retrieve the data and then investigate the response to check for errors and then either process the error or parse the JSON. Note that the promise ‘then’ clause is used even in the case of a unsuccessful HTTP response code. That is why the response.ok check is made. If that is unsuccessful, the error handler is still invoked.
In addition, it’s important to check the response body when processing errors as that is where detail error cause information will be found.
Sample 2 – XMLHttpRequest request
In our second 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 3 – 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 4 – 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 4 – 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) { var location=response.resolvedAddress; var days=response.days; console.log("Location: "+location); for (var i=0;i<days.length;i++) { console.log(days[i].datetime+": tempmax="+days[i].tempmax+", tempmin="+days[i].tempmin); } }
The response contains overall information about the requested 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 API documentation. You can also preview live JSON in the Query Builder Tool:
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 need help?
If you have a question or need help, please post on our actively monitored forum for the fastest replies. You can also contact us via our support site or drop us an email at support@visualcrossing.com.