0

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.

1 Answer 1

1

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
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.