So, I'm making a bunch of webpages for different communities, and on each I want to have a little weather box that I can customize, just with the name of the town, the current temperature, and the current weather condition. I want to be able to style it all exactly how I want. I found this site called Open Weather Map that seems to do exactly what I want. The problem is that I don't know how to use JSON. It's probably easy, but I seem to have gotten lost on any online tutorials I've tried.
This is an example of a URL for the page, that loads some JSON. http://api.openweathermap.org/data/2.5/weather?q=London,uk
I could just include this in my file and dynamically change the city and the country code to get the city I want. But how do I load this into my weather box? Let's say this is what I have:
<div class="weatherbox">
<strong class="city>{CITY NAME HERE}</strong>
<span class="temperature">{X} °C</span>
<p class="weatherdescription>{WEATHER DESCRIPTION HERE}</p>
</div>
Then how do I access the data from the JSON? I want it to be done as simply as possible. Do I include the file like this to have access to the object, or is it more complicated?
<script type="javascript" src="http://api.openweathermap.org/data/2.5/weather?q=London,uk"></script>
from your line of code:
<script type="javascript" src="http://api.openweathermap.org/data/2.5/weather?q=London,uk"></script>
this is incorrect, the api is returning JSON, it is not a javascript file so you don't access it in such a manner. Note that their API appears to take the city and country as a part of the URL parameters, so this you will need to plug in for the appropriate city/country.
For your specific question you could do something like:
var jsonData;
$(document).ready(function ()
{
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=London,uk', function(data) {
jsonData = data;
$('.city').text(jsonData.name);
// etc
});
});
See http://jsfiddle.net/jsxm7j3n/1/ for it in action.
Note in order to understand the JSON, you can run it through a JSON parser such as the one at http://json.parser.online.fr/ - this will allow you to better understand the make up of what you're receiving back, and how to parse it.
Double note: forgot to mention this solution uses JQuery - i believe there are purely javascript ways to pull it off, but it will be much more verbose and (in my opinion) harder to understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With