Reputation: 5953
I have just created an account with OpenWeatherMap
I want to get the current weather for location by City ID API Call:
http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey
On my html page, how do I go about using this so that I can show my users what the weather is for the specific location?
I have used Yahoo Weather API, but want to try something different. Is the process similar? I don't see where I would call a callbackfunction like in yahoo weather api.
Do I have to write something like this?
<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>
I have tried this and it is not working.. and I couldn't find any examples on the website on how to integrate this into my html page.
Any help is appreciated.
UPDATE:
I have tried:
<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />
This uploads a black x.. not the picture of the current weather.
UPDATE:
I have found that I need to use ajax.. here is what I have so far:
<script>
$(document).ready(function () {
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id: '2172797', appid: 'myapikey' },
success: function (response) {
var dataArray = JSON.parse(response);
var weatherIcon = dataArray.weather.icon;
var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
document.getElementById('Weather-Image').src = iconUrl;
}
});
});
</script>
Upvotes: 0
Views: 967
Reputation: 748
The data returned from http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey
is described in the documentation of OpenWeatherMap.
You can't use it directly in a <script>
or <img>
tag as the response is JSON.
If you must use JavaScript to fetch the weather data, you will need AJAX (or any AJAX wrapper like $.ajax
from jQuery) to call the API url then use JSON.parse
to create an array with all the given data.
This is how it could look like:
var request = $.ajax({
url: "http://api.openweathermap.org/data/2.5/weather",
method: "GET",
data: { id : '2172797', appid: 'myAPIKey'},
success: function(response) {
// response from OpenWeatherMap
var dataArray = JSON.parse(response); // create an array from JSON element
}
});
Upvotes: 2