【问题标题】:OpenWeatherMap StartingOpenWeatherMap 开始
【发布时间】:2016-12-08 15:31:11
【问题描述】:

我刚刚用OpenWeatherMap创建了一个帐户

我想通过 City ID API 调用获取当前位置的天气:

http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myAPIKey

在我的 html 页面上,我该如何使用它,以便向我的用户展示特定位置的天气情况?

我使用过 Yahoo Weather API,但想尝试一些不同的东西。过程类似吗?我看不出我会在哪里调用像在 yahoo 天气 api 中那样的回调函数。

我必须写这样的东西吗?

<script src="http://api.openweathermap.org/data/2.5/weather?id=2172797&mode=html&appid=myapikey"></script>

我已经尝试过了,但它不起作用..我在网站上找不到任何关于如何将其集成到我的 html 页面中的示例。

感谢任何帮助。

更新:

我试过了:

<img id="Weather-Image" src="http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=myapikey" />

这会上传一个黑色的 x.. 不是当前天气的图片。

更新:

我发现我需要使用 ajax.. 这是我目前所拥有的:

<script>
    $(document).ready(function () {
        var request = $.ajax({
            url: "http://api.openweathermap.org/data/2.5/weather",
            method: "GET",
            data: { id: '2172797', appid: 'myapikey' },
            success: function (response) {
                var dataArray = JSON.parse(response);
                var weatherIcon = dataArray.weather.icon;
                var iconUrl = "http://openweathermap.org/img/w/" + weatherIcon + ".png";
                document.getElementById('Weather-Image').src = iconUrl;
            }
        });
    });
</script>

【问题讨论】:

    标签: javascript html openweathermap


    【解决方案1】:

    http://api.openweathermap.org/data/2.5/weather?id=2172797&amp;appid=myAPIKey 返回的数据在OpenWeatherMap 的文档中有描述。

    您不能直接在 &lt;script&gt;&lt;img&gt; 标记中使用它,因为响应是 JSON。

    如果您必须使用 JavaScript 来获取天气数据,您将需要 AJAX(或任何 AJAX 包装器,如来自 jQuery 的 $.ajax)来调用 API url,然后使用 JSON.parse 创建一个包含所有给定数据的数组。

    这就是它的样子:

    var request = $.ajax({
      url: "http://api.openweathermap.org/data/2.5/weather",
      method: "GET",
      data: { id : '2172797', appid: 'myAPIKey'},
      success: function(response) {
          // response from OpenWeatherMap
          var dataArray = JSON.parse(response); // create an array from JSON element
      }
    });
    

    【讨论】:

    • 好的,你能给我一个代码示例吗?我发现我需要使用ajax,但我无法编写它
    • @BviLLe_Kid 我为 AJAX 添加了一个代码示例并实现了JSON.parse 行。
    • 好的,我有你发布的内容。 idappid 如何集成到 url 中?
    • 忘记我的问题,数据附加到获取请求的 url
    • 您还需要什么?我看到您已经尝试获取图标
    猜你喜欢
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2018-06-05
    • 2015-01-04
    • 2014-01-21
    • 2014-08-16
    • 2017-03-18
    相关资源
    最近更新 更多