API intergration via JQuery
In the Thermostat work, we need a weather API in order for the user to see the local weather.
We can use $.get()
in order to call for an API in the console:
// Console
$.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=b0bd65ce52a561a2932b1512a37ebb87', function(data) {
console.log(data);
})
In regards to the API pathing, it's important to note that we need to cobble together what we want. In the example able, we specified that we wanted the weather in London in the first part. From there, we specify our own personalised API key under the appid
part.
We can refer to how $.get()
works via the JQuery site: http://api.jquery.com/jQuery.get/
As the documentation says, $.get()
is shorthand for $.ajax()
which is a wrapper around JavaScript's inbuilt XMLHttp
library.
We can click on the console printout to see what's in the object. When we look at the temperature , it's showing something like 280 degrees. We can specify metric:
// console
$.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=b0bd65ce52a561a2932b1512a37ebb87&units=metric', function(data) {
console.log(data.main.temp);
})
The above get call has been edited to specifically grab metric figures. The console log has also been edited so that it only goes through data{main{temp}}.
Now that the information has been drilled down, we can start applying the .html
file, and then add the JQuery to reference where to display the data on the page.
<h1>Current temperature: <span id=weatherAPI></span></h1>
<script>
$.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=b0bd65ce52a561a2932b1512a37ebb87&units=metric', function(data) {
$('#weatherAPI').text(data.main.temp);
})
</script>