Javascript – Using weather API with JSON and JavaScript/jQuery

javascriptjqueryjsonopenweathermapweather-api

I've found this free weather API that gives you a forecast when you send an HTTP GET request – the forecast is delivered in JSON. A request could look like this:

Examples of JSON format:
Seaching by city name:
api.openweathermap.org/data/2.5/weather?q=London,uk
Seaching by geographic coordinats:
api.openweathermap.org/data/2.5/weather?lat=35&lon=139 Seaching by
city ID:
api.openweathermap.org/data/2.5/weather?id=2172797

So the response you get back is obviously defined by the end of the url, where some variables are located.

I've seen that you can use the jQuery function getJSON() to create an object out of the text file you get with an HTTP GET request, and you can also use variables with it to change the url. For an example doing this:

var person = "john";
$.getJSON("https://graph.facebook.com/" + person, function(person){

    $.each(person, function(key, value){
        document.write(key+": "+value+"<br />"); 
    });
}); 

Gives the output

id: 779695190
first_name: John
gender: male
last_name: Chan
locale: en_US
name: John Chan
username: John

However, when I try to use this with the weather API it doesn't work – there is no output. (Doing it without url-variables here for simplicity.) The below code is how I thought it would be done (but apparantly not).

$.getJSON("api.openweathermap.org/data/2.5/weather?q=London,uk", function(forecast){
    var temperature = forecast.main.temp;
    document.write(temperature);
});

See the JSON structure for the forecast here: http://bugs.openweathermap.org/projects/api/wiki/Weather_Data

So basically my questions are: How would I append the url-variables to the weather-api-urls (and making sure the request can be both city name or coordinates)? And how would I access the retrieved data once I got it from the server?

Best Answer

first you can read the lat & long values or the zip code or city ID and then can append them by calling the functions which includes the ajax to call the api wrt to the given parameter.See below i have tried it using just the lat long values from the browser.after getting the results you can access them like any other json object.

function success(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    var timstp = position.timestamp;
    var myDate = new Date(timstp).toLocaleString();
    //console.log("Lat="+lat+"Long="+long+"timstp="+timstp+"date="+myDate); 

    $.ajax({
      url: "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + long + "&appid=690660b930904f0cee1975853d5a2375",
      dataType: 'jsonp',
      success: function(results) {
        console.log(results);

   
      }
    });
}