如何使用这个api返回温度?用JavaScript?

时间:2015-12-22 23:20:17

标签: javascript html api weather-api

嗨我得到了这段代码,并希望在此基础上进行构建,以便恢复温度。

我正在使用OpenWeatherMap API。以下是从

中提取信息所需的代码
{  
   "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
}

我已经加入了我认为需要使用的粗体。

我已经在调出一些信息,如下所示。

虽然当我尝试按照这个并添加更多代码时,它会中断并返回任何内容。

我认为它就在这里。我甚至可能需要制作一个新的var?为它

即var temp ......但接下来我无法理解。

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

然后当这个被修复时,我需要改变温度,以便它显示在我设置的div中?

感谢任何帮助,

感谢,

扎克

1 个答案:

答案 0 :(得分:0)

以下是我的表现。

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