33

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Ajay Krishna Dutta
  • 722
  • 2
  • 7
  • 21

20 Answers20

63

Well, I know a 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 variable 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);
user11877521
  • 319
  • 2
  • 11
samu101108
  • 675
  • 7
  • 23
58

You can get OpenWeatherMap API icons through this link. All you need to do is that moderate the icon id given in bold below in this link. You can change 10d with any icon id that you need.

http://openweathermap.org/img/w/10d.png

For more information, You can read here OpenWeatherMap Icons

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Mukhammad Ali
  • 810
  • 7
  • 14
9

So I spent a lot of time solving this problem. This answer is for pure HTML and JavaScript and if you don't want to use jquery.

1- Include the "icons" file in your program: openweatherAPI Icons integration

2- In your index.html :

<div class="weather-icon"><img src="icons/unknown.png" /></div>

3- In your JavScript file(follow these 3 steps in your JS code) :

1st Step: let locationIcon = document.querySelector('.weather-icon');

2nd Step: const {icon} = data.weather[0];

3rd Step(not in code format, as it was making thebackticks part disappear):
locationIcon.innerHTML = <img src="icons/${icon}.png">;

Worked just fine for me. Happy building.

yuvraaaj
  • 91
  • 1
  • 2
  • 7
  • 1
    i was struggling trying to understand your step 3.. but at the end I figured it oit and it works, thanks – Ruvalcaba Sep 23 '20 at 18:08
  • Yeah I am sure you are talking about 3rd step in 3. I am still not sure if the code insertion feature on stackoverflow allows you to type the code with backticks, which we usually use in JavaScript. – yuvraaaj Oct 01 '20 at 12:32
  • The 3rd part of the 3rd step needs the backticks for the HTML image element. Like this `locationIcon.innerHTML = \`;\`` Shouldn't step 2 come before step 1 in the third part in setting up the JS? Because the variable of icon needs to be initialized first. I'd also suggest an edit on the "second step" of the code to change to this `const icon = data.weather[0].icon` as it's an array containing an object and a property of icon that we're trying to get. – Dan Apr 07 '21 at 03:45
6

This code works for me in React Native:

const icon = wInfo.weather[0].icon; // For instance "09d"
<Image source={{ uri: ``http://openweathermap.org/img/w/${icon}.png`` }} />
Manoj
  • 2,059
  • 3
  • 12
  • 24
Clau
  • 86
  • 1
  • 2
5

the src of the icon would be like this:

http://openweathermap.org/img/wn/10d@2x.png

see Weather icons

Developer Hub
  • 183
  • 3
  • 13
2

Thank you all very much! I am a very beginning Flutter programmer and wanted to display the Icon in the Weatherapp, we made on course with Angela Yu.

I did this in Flutter:

String weerImageString;
weerImageString = weatherData['weather'][0]['icon'];

and then were I wanted it to display, I did:

Image.network('http://openweathermap.org/img/w/$weerImageString.png',),

I hope that I can someday helping someone with this. And... if there is an easier way, I would love to hear!

Margriet
  • 197
  • 2
  • 10
2

For react, you can use like this:

Step 1: initialize blank state

constructor(){
    super()
        this.state={
            icon:''
        }
    }

Step 2: api call

async componentDidMount(){
            const url = 'http://api.openweathermap.org/data/2.5/'
            const key = 'your api key'
            const response = await fetch(`${url}weather?q=Guwahati&units=metric&APPID=${key}`)
            const data = await response.json() //this will return the json response
            const iconName = data.weather[0].icon // this will hold the icon
            const iconApi = await fetch('http://openweathermap.org/img/w/' + iconName + '.png')
            this.setState({
                icon : iconApi.url
            })
        }
    

Step 3: Display icon

    <div className="weather-icon">
         <img style={{width:'70px'}} src= {this.state.icon} />
    </div>
Stu Furlong
  • 3,490
  • 5
  • 34
  • 47
Rahul Sarma
  • 763
  • 2
  • 8
  • 17
1

Here d refers to day, like n refers to night. And based on weather status it will change, e.g. 03d for scattered clouds, 01d for clear sky etc. Here you will get a full list of these icons https://openweathermap.org/weather-conditions#How-to-get-icon-URL

Rahul Sarma
  • 763
  • 2
  • 8
  • 17
1

This answer is in reference to the Android, so after struggling for few hours I finally figured out how to display icons from openweathermap api.

The URL is https://openweathermap.org/img/w/${icon_id}.png

Just put the icon Id you are getting from the API and you will get the result. Common mistakes which I faced were :

  1. Not using https, as I was using http and it was not working

  2. Also you can get bigger size image by using :

     url - https://openweathermap.org/img/wn/${icon_id}@4x.png 
    

icon_id examples : 04d, 10d

working response : https://openweathermap.org/img/wn/04d@4x.png

oyeraghib
  • 878
  • 3
  • 8
  • 26
1

This is what I did and it worked for me. You see, from the response object map through it and with the result access icon as follows

<img src="http://openweathermap.org/img/w/${result.icon}.png" alt="img">
Kipruto
  • 721
  • 6
  • 16
1

This is how i solved it. Totally works. no need for JQuery or any of those. First thing is you realize that the api route is in an array in the weather tab so u have to parse it correctly. use console.log to make sure the get the "10n" kind of result so u know you are getting the right output. then you use this img tag <img alt="icon" src={http://openweathermap.org/img/w/${icon}.png} width="120" height="100" />

where icon is the string "04n" that you get from the parsed data. then it should work perfectly. Below is my parsed data example. you can see i am geting the temp, humidity, dt_txt is one of the results and icon is the icon

( { main: { temp, humidity }, dt_txt, weather: [{ icon }] }, index )

Ifeanyi
  • 11
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 13 '22 at 06:42
1

Firstly, 10d is the icon id that changes according to the forecast data. I was doing a react weather-App project, and I did the following in my component:

<div>
    <img 
    id="wicon" 
    src={`http://openweathermap.org/img/wn/${a.weather[0].icon}@2x.png`}
    alt="weather icon">
    </img>
</div>

This way if the value of the icon change it automatically changes in the Dom.

0

This worked for me!

  1. create variable to access data between javascript and HTML.
    var var1 = document.querySelector('idhere') // you have to use parent class/id

  2. Get icon from JASON
    var tempvariable = data['weather'][0]['icon'];

  3. pass link along with html tag to html
    var1.innerHTML = "http://openweathermap.org/img/w/" +tempvariable+ ".png' alt='Icon depicting current weather.'>"

or

var1.innerHTML = "http://openweathermap.org/img/w/" +data['weather'][0]['icon']+ ".png' alt='Icon depicting current weather.'>"// step 2 is not required if you use this method.

Varun Rao
  • 1
  • 2
0

http://openweathermap.org/img/wn/$weatherData.weather[0].icon@2x.png

To display this on a webpage, you could just add it to the src attribute of an img tag.

This is what the URL for getting the icon will look like.... Where weatherData is the data that you get from the API call you make to the OPENWEATHERMAP. It comes in JSON format. You need to parse.

0

I think you are asking about IconCode

https://openweathermap.org/ to get converted to an image

For example 02n =>img

So, if thats what you want, then:

  1. You need to use this link
    https://openweathermap.org/img/wn/02n@2x.png
  2. Replace the '02n' with the image codes you get as a response
  3. Done

For more image codes information Go to link

MaxiGui
  • 6,190
  • 4
  • 16
  • 33
Ali Tasawar
  • 104
  • 4
0

const icon = `https://openweathermap.org/img/wn/${weather[0]["icon"]}@2x.png`;

const li = document.createElement("li");
    li.classList.add("city");
       const markup = `
          <figure>
              <img class="city-icon" src=${icon} alt=${weather[0]["main"]}>
              <figcaption>${weather[0]["description"]}</figcaption>
          </figure>
                `;
li.innerHTML = markup;
Eli
  • 1
0

Your html file:

<div class="weather">
  <form class="weather-form">
    <input type="text" class="city-name">
    <input type="submit">
  </form>
  <img src="" class="iconurl">
</div>

Your JS file:

// hit API

const getWeather = async (cityname) => {
  let response = await fetch('https://api.openweathermap.org/data/2.5/weather?q=' + cityname + '&appid=${API KEY}') //you get your api key once you sign up for openweathermap.org
  return response.json()
}

// DOM

const weatherContainer = document.querySelector('.weather')
const weatherForm = document.querySelector('.weather-form')
const iconurl = document.querySelector('.iconurl')

// Event Listener

weatherForm.addEventListener('submit', (e) => {
  e.preventDefault()

  const cityInput = document.querySelector('.city-name')

  getWeather(cityInput.value).then(c => {
    c.weather.forEach(ww => {
      let url = "http://openweathermap.org/img/w/" + ww.icon + ".png"
      iconurl.src = url
    })
  })
})
  • Please add some possible information/explanation over how its works, instead of just answer to this question. Explanation helps to understand and useful for similar questions – Aishwarya Dec 30 '21 at 05:54
0

I had a same problem in Flutter/Dart but not only can't display weather icon but also icon string doesn't have a "http:" in response. I'm working on weatherapi.com.

Here's how You do it in FLUTTER/DART and I'm using Dio package(not http): In model that You build You need to add: icon_url = "http:" + json['current']['condition']['icon'] - I did it with "http:" first cause as I said, response doesn't have it in icon url, otherwise just use rest of the code if You're using openweathermap, parameters in [] are just parameters from response, change them, depended on your API. To display icon use Image.network( nameofyourModel.icon_url). Hope it helps somebody !

-1

ExpressJS: First Get Icon:
const icon = weather.weather[0].icon;

Second: iconurl= http://openweathermap.org/img/wn/${icon}.png;

Third: " alt="">

-1

A little late I must admit. I'm at University right now and I had the same experience as you, where I didn't know how to get the icon to work.

However, a guy at University was kind enough to give me help, which I appreciate very much.

So, in your Javascript, you put:

document.getElementById("icon").src = "https://openweathermap.org/img/wn/" + response.weather[0].icon + "@2x.png";

And in your HTML, you put:

<img id="icon" src = "" alt = "Weather icon"> 

Hope this helps anyone who was in the same situation as me :)

Thanks!

Josh Smith
  • 17
  • 4