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

49

我正在使用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返回的温度单位是什么吗?


有人点赞了我的回答,我想记住它是关于什么的,所以我点击了进去。看到了回答中的讽刺语气,吓了一跳。完全没有必要这样做。我已经删除了那段讽刺的话,并为此道歉。祝编码愉快! - T.J. Crowder
6个回答

165

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

查看API文档,如果在请求中添加&units=metric,则会返回摄氏度。


@TJCrowder 这不是一个有点奇怪的默认设置吗? - hitautodestruct
4
对我来说是这样,但是我不是科学家。 :-) - T.J. Crowder
4
开尔文(Kelvin)是“国际单位制”中的温度单位。它是绝对的,基于物理学。它的零点是“绝对零度”。对我来说,它似乎是一种相当自然的“默认选择”。 - MarcoS
1
@MarcoS:当然,但这是天气信息。99.999999%的人使用摄氏度或华氏度来消费天气信息,甚至(我愿打赌)大多数气象学家也是如此。默认值是针对常见情况而不是百万分之一的情况。 :-) - T.J. Crowder
我认为这是某种“内部格式”……这样用户就被“迫”选择她偏好的“常见”单位…… - MarcoS
2
我的英雄走了,看着他走。甚至没有看到&units文档。 - ReSpawN

14

感谢您抽出时间回答! - hitautodestruct
1
@spacebean,它显示的错误如下:{"cod":401, "message": "无效的 API 密钥。请参阅 http://openweathermap.org/faq#error401 了解更多信息。"} - Kedar Kodgire
如果您使用 &lat=...&lng=...&units=metric,它将不再起作用。请注意。 - tree em

5

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
尝试这个例子。
curl --location --request GET 'http://api.openweathermap.org/data/2.5/weather?q=Manaus,br&APPID=your_api_key&lang=PT&units=metric'

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接