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

问题描述 投票:0回答:7

我正在使用 openweathermap.org 获取某个城市的天气。

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 返回的温度单位是什么?

javascript json units-of-measurement weather-api openweathermap
7个回答
166
投票

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

查看 API 文档,如果您将

&units=metric
添加到您的请求中,您将返回摄氏度。



5
投票

开尔文到华氏度是:

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

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


1
投票

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

这是我的代码。

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

1
投票

首先确定您想要哪种格式。 在 BASE_URL 中发送城市后,仅添加 &mode=json&units=metric。您将从服务器获得直接的摄氏度值。


1
投票

尝试这个例子

curl --location --request GET 'http://api.openweathermap.org/data/2.5/weather?q=Manaus,br&APPID=your_api_key&lang=PT&units=metric'

0
投票

或者您可以创建一个像这样带有一个参数的简单函数! (摄氏度)

export function transformTemperature(data) {
    let temperature = data;
    let celsius = temperature - 273;
    let roundedTemp = Math.round(celsius)

    return roundedTemp
}
© www.soinside.com 2019 - 2024. All rights reserved.