如何计算openweathermap.org JSON中返回的摄氏温度?

问题描述:

我正在使用openweathermap.org获取城市的天气。如何计算openweathermap.org JSON中返回的摄氏温度?

的JSONP调用工作,一切都很好,但由此产生的对象包含一个未知的装置温度:

{ 
    //... 
    "main": { 
     "temp": 290.38, // What unit of measurement is this? 
     "pressure": 1005, 
     "humidity": 72, 
     "temp_min": 289.25, 
     "temp_max": 291.85 
    }, 
    //... 
} 

这里是一个演示是console.log的完整的对象。

我不认为产生的温度是华氏温度,因为将290.38华氏度转换为摄氏温度是143.544

有谁知道什么温度单位openweathermap返回?

看起来像kelvin。将开尔文转换为摄氏温度很简单:只需减去273.15。在the API documentation

而且最短一目了然告诉我们,如果你添加&units=metric你的要求,你会回来摄氏度。

+0

@TJCrowder这不是一个有点奇怪的默认设置吗? – hitautodestruct

+3

@hitautodestruct:这是*我*,但是,我不是科学家。 :-) –

+4

Kelvin(http://en.wikipedia.org/wiki/Kelvin)是“国际单位制”的温度单位。这是绝对的,基于物理学。零是“绝对零”。它看起来是一个相当自然的选择,对我来说,“默认”... – MarcoS

+0

感谢您花时间回答! – hitautodestruct

+0

@spacebean它显示如下错误:'{“cod”:401,“message”:“无效的API密钥,请参阅http://openweathermap.org/faq#error401了解更多信息。”} –

开到华氏是:

((kelvinValue - 273.15) * 9/5) + 32 

我注意到,如果传入的参数不是所有的OpenWeatherApp调用都会读取单位参数。 (此错误的一个示例: http://api.openweathermap.org/data/2.5/group?units=Imperial&id=5375480,4737316,4164138,5099133,4666102,5391811,5809844,5016108,4400860,4957280&appid=XXXXXX) 仍然返回开尔文。

您可以将单位更改为公制。

这是我的代码。

<head> 
    <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script> 
     <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script> 
     <style type="text/css">] 
     body{ 
      font-size: 100px; 

     } 

     #weatherLocation{ 

      font-size: 40px; 
     } 
     </style> 
     </head> 
     <body> 
<div id="weatherLocation">Click for weather</div> 

<div id="location"><input type="text" name="location"></div> 

<div class="showHumidity"></div> 

<div class="showTemp"></div> 

<script type="text/javascript"> 
$(document).ready(function() { 
    $('#weatherLocation').click(function() { 
    var city = $('input:text').val(); 
    let request = new XMLHttpRequest(); 
    let url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=[YOUR API KEY HERE]`; 


    request.onreadystatechange = function() { 
     if (this.readyState === 4 && this.status === 200) { 
     let response = JSON.parse(this.responseText); 
     getElements(response); 
     } 
    } 

    request.open("GET", url, true); 
    request.send(); 

    getElements = function(response) { 
     $('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`); 
     $('.showTemp').text(`The temperature in Celcius is ${response.main.temp} degrees.`); 
    } 
    }); 
}); 
</script> 

</body>