OpenWeatherMap 开始

OpenWeatherMap Starting

我刚刚用 OpenWeatherMap

创建了一个帐户

我想通过城市 ID 获取位置的当前天气 API 呼叫:

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

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

我使用过 Yahoo Weather API,但想尝试一些不同的东西。过程是否相似?我不知道在哪里可以像雅虎天气那样调用回调函数 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>

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

您不能直接在 <script><img> 标签中使用它,因为响应是 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
  }
});