yuriy636
yuriy636

Reputation: 11661

[JS,JSON]Open Weather Map API: JSON call and parse to JS var

I want to make a call to OpenWeatherMap API with javascript (and maybe jQuery?) to this URL

http://api.openweathermap.org/data/2.5/weather?lat=(here comes the lat for a variable)&lon=(lon from variable)

Then parse the API output(It's JSON I think) to get the

 "main":"Clear" and "temp":271.997

And set the "main" and "temp" variables to js variables, and send them to innerHTML.

Can somebody make a script example, please?

Thanks for the help and sorry the bad english.

Upvotes: 0

Views: 2667

Answers (1)

Dolores
Dolores

Reputation: 323

Because you are parsing a json file that is on another server (not local) you will need to use JSONP. Essentially you use ajax to pass a callback parameter to open weather map. This enables you to use the data in your script.

The following jquery will use coordinate variables to generate a link to the json file, parse the data using jsonp and display the information in a web element with id "weather".

You will most likely want to add error handling and create a local cache of the data for visitors, and then load the cache if it is recent. I hope this helps you out.

var lat=00.00 //latitude variable
var long=00.00 //longitude variable
var data_url="http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon="+long+"";
//function to pull information out of the json file and stick it into an HTML element
getWeather(function (data) {
    var weather_html = data.weather[0].description + "nbsp;" + data.main.temp;
    document.getElementById('weather').innerHTML = weather_html;
});
// function to use jsonp to get weather information
function getWeather(callback) {
    $.ajax({
        dataType: "jsonp",
        url: data_url,
        success: callback
    });
};

Upvotes: 1

Related Questions