How to display openweathermap weather icon

Ajay Krishna Dutta picture Ajay Krishna Dutta · May 25, 2017 · Viewed 63.6k times · Source

I am using openweathermap to display weather reports. Everything is working fine but there is a problem with the icon. The JSON response code is:

Array
(
    [city] => Array
        (
            [id] => 1271476
            [name] => Guwahati
            [coord] => Array
                (
                    [lon] => 91.751
                    [lat] => 26.1862
                )

            [country] => IN
            [population] => 899094
        )

    [cod] => 200
    [message] => 0.0630711
    [cnt] => 1
    [list] => Array
        (
            [0] => Array
                (
                    [dt] => 1495688400
                    [temp] => Array
                        (
                            [day] => 33
                            [min] => 24.89
                            [max] => 33.82
                            [night] => 24.89
                            [eve] => 30.6
                            [morn] => 33
                        )

                    [pressure] => 1013.02
                    [humidity] => 90
                    [weather] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 500
                                    [main] => Rain
                                    [description] => light rain
                                    [icon] => 10d
                                )

                        )

                    [speed] => 3.92
                    [deg] => 88
                    [clouds] => 24
                    [rain] => 2.73
                )

        )

)

Now how can I display the icon: [weather][0][icon] => 10d?

What is 10d & how can I get the URL of the icon?

Answer

samu101108 picture samu101108 · Mar 20, 2018

Well, I know an way using jQuery.

  <div id="icon"><img id="wicon" src="" alt="Weather icon"></div>

At the HTML above you see the unique thing missing is the src attribute, so let's fill it with some jQuery and JavaScript. You may create a variables to hold the icon code provided by the API like:

        var iconcode = a.weather[0].icon;

After it you should concatenate this var iconcode with the url that contains the icons, like:

        var iconurl = "http://openweathermap.org/img/w/" + iconcode + ".png";

Finally just change src attribute in the DOM by doing this:

        $('#wicon').attr('src', iconurl);

I hope this solve the issue. :)