How to display openweathermap weather icon

Viewed 109406

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?

17 Answers

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.

the src of the icon would be like this:

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

see Weather icons

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`` }} />

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!

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>

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

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.

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.

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;

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">

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
    })
  })
})

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 )

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

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

Third: " alt="">

Related