使用OpenWeatherMap取得天氣狀況

OpenWeatherMap是一個提供全世界天候資訊的網站,同時也開放API給外界讀取他們的資料。今天就以這個服務來建立天候預報。

準備工作

API 回傳資料JSON內容

{
  "city": {
    "id": 1850924,
    "name": "Takatorichō",
    "coord": {
      "lon": 135.133331,
      "lat": 34.650002
    },
    "country": "JP",
    "population": 0,
    "sys": {
      "population": 0
    }
  },
  "cod": "200",
  "message": 0.0272,
  "cnt": 34,
  "list": [
    {
      "dt": 1456941600,
      "main": {
        "temp": 277.58,
        "temp_min": 273.421,
        "temp_max": 277.58,
        "pressure": 1022.93,
        "sea_level": 1038.49,
        "grnd_level": 1022.93,
        "humidity": 71,
        "temp_kf": 4.15
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01n"
        }
      ],
      "clouds": {
        "all": 0
      },
      "wind": {
        "speed": 3.67,
        "deg": 239.002
      },
      "rain": {
      },
      "snow": {
      },
      "sys": {
        "pod": "n"
      },
      "dt_txt": "2016-03-02 18:00:00"
    },
    ...
  ]
}

作法一:透過Client Ajax 方式直接連線API取得氣候資料

function buildHTML(data, i) {
  var Week = new Array("(日)","(一)","(二)","(三)","(四)","(五)","(六)");
  var date = new Date (data.list[i].dt_txt);
  date.setHours(date.getHours() + 9);
  var month = date.getMonth()+1;
  var day = month + "月" + date.getDate() + "日" + Week[date.getDay()] + date.getHours() + ":00";
  var icon = data.list[i].weather[0].icon;
  var html =
  '<div class="weather-report">' +
    '<img src="http://openweathermap.org/img/w/' + icon + '.png">' +
    '<div class="weather-date">' + day + '</div>' +
    '<div class="weather-main">'+ data.list[i].weather[0].main + '</div>' +
    '<div class="weather-temp">' + Math.round(data.list[i].main.temp) + '℃</div>' +
  '</div>';
  return html
}

$(function() {
  var API_KEY = '*******************************'
  var city = 'Taipei';
  $.ajax({
    url: 'http://api.openweathermap.org/data/2.5/forecast?q=' + city + ',jp&units=metric&APPID=' + API_KEY;,
    dataType: "json",
    type: 'GET',
  })
  .done(function(data) {
    var insertHTML = "";
    var cityName = '<h2>' + data.city.name + '</h2>';
    $('#city-name').html(cityName);
    for (var i = 0; i <= 8; i = i + 2) {
      insertHTML += buildHTML(data, i);
    }
    $('#weather').html(insertHTML);
  })
  .fail(function(data) {
     console.log("資料取得失敗");
  });
});