How to get and post the icons from open weather api to html?

How to get and post the icons from open weather api to html?
0

#1

I am able to get the temperature and other things from the open weather api, but for some reason, I cannot get the icon, even when I attempt to access it in the same way that I get the temp. How can I get the icon successfully? When I do get the icon, what is the best way to post it to the page html- wise? Here is the code that I am currently working with:

$.getJSON(“http://ip-api.com/json”, function(json) {
var result = JSON.stringify(json);
var user_city = json.city;
var user_lon = json.lon;
var user_lat = json.lat;

$(".message").html(JSON.stringify(json));

$.getJSON("http://api.openweathermap.org/data/2.5/weather" + '?lat=' + user_lat + '&lon=' + user_lon + "&appid=" + "8df1c0043704c7a3944e6afaa07200fb", function(json) {   
var temp = json.main.temp; //unit is kelvin
 
  var icon = json.weather.icon +".png";
  
  console.log(user_city); // This works
console.log(temp); // This works
  console.log(icon); // This doesn't work 
  


});

});

Thanks!


#2

Hi. I examined the JSON and found out that weather in json.weather.icon is actually an array.

...
  'weather': [
    {
      'id': 800,
      'main': 'Clear',
      'description': 'clear sky',
      'icon': '02d'
    }
  ],
...

To get the icon, you’ll have to use json.weather[0].icon instead.


#3

Thanks for the help! Now that I am getting the icon code, what is the best way to display it html-wise? Any specific examples would be great!
Thanks again!


#4

I haven’t started that project yet, so I can’t help with that. :frowning:


#5

Well, you probably already know that you can write html to the page using jQuery - that’s how you’re writing your ‘message’ to the screen in you original code snippet.

What you’re actually writing to the screen in that example is just some text, though. You can build whole HTML strings out and have them render on the page. For example, a jQuery snippet that writes an image to the page would look like this:

$(".icon").html("<img src=' + icon + '>");

Assuming you have an icon class to pin it to, and your icon variable contains the appropriate file location for the image.


How to display the weather icon?