How to use this api to return the temperature? With JavaScript?

*爱你&永不变心* 提交于 2019-12-13 05:27:24

问题


Hi I was given this code and want to build upon it so that the temperature is also returned.

I am using OpenWeatherMap API. Here is the code that I need to pull the information from

{  
   "coord":{  
      "lon":98.86,
      "lat":55.08
   },
   "weather":[  
      {  
         "id":801,
         "main":"Clouds",
         "description":"few clouds",
         "icon":"02n"
      }
   ],
   "base":"cmc stations",
   "main":{  
      "temp":245.781,
      "pressure":969.38,
      "humidity":48,
      "temp_min":245.781,
      "temp_max":245.781,
      "sea_level":1050.78,
      "grnd_level":969.38
   },
   "wind":{  
      "speed":1.07,
      "deg":138.501
   },
   "clouds":{  
      "all":12
   },
   "dt":1450824930,
   "sys":{  
      "message":0.0075,
      "country":"RU",
      "sunrise":1450748926,
      "sunset":1450774674
   },
   "id":1488616,
   "name":"Uk",
   "cod":200
}

I have put in bold what I think I need to use.

As I am already calling out some information as you can see below.

Though when I try to follow this and add more code it breaks and returns nothing.

I think it is here. I might even need to make a new var? for it

i.e var temp... but what come next I can't get my head around.

var weather = json.weather[0].main
                setIconAndDescription(weather, location)

            }
            else {


                description = "Oops, I couldn't find the weather in " + location;
                document.getElementById("description").innerHTML = description;

            }
        }
    }
}

function setIconAndDescription(weather, location){

    var icon;
    var description;


    weather = weather.toLowerCase();


    if (weather == "clear sky"
        || weather == "clear"){

        icon = "clear.svg";
        description = "Yay, sunshine!";
        document.body.style.backgroundColor = "#FA6144";
        document.getElementById("icon").style.backgroundColor = "#7A2F21";
            document.getElementById("temp").style.backgroundColor = "#7A2F21";
        document.getElementById("description").style.backgroundColor = "#E0563D";

Then when this is fixed I am then need to change the temperature so that it displays itself inside a div I have set up?

Any help is appreciated,

thanks,

Zack


回答1:


Here's how I'd do it.

// Get the temperature
var temp = json.main.temp

// Get your div you want to put it in
var mydiv = document.getElementById('mydivid')

// Set the inner HTML as that temperature (plus units, in your case, kelvin I guess)
mydiv.innerHTML(temp + "K")


来源:https://stackoverflow.com/questions/34426090/how-to-use-this-api-to-return-the-temperature-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!