5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails/ES6/OpenWeatherMapで天気予報を表示してみた

Last updated at Posted at 2020-12-02

ezgif.com-gif-maker.gif

#開発環境
Ruby: 2.6.5
Rails: 6.0.0

事前準備

OpenWeatherのHPにアクセスしアカウントを作成してください。

私は下記記事を参考にアカウントを作成しました。
【Rails】OpenWeatherMapを用いて、登録住所の天気予報を、日本語で表示する方法

実装

app/controllers/weathers_controller.rb
class WeathersController < ApplicationController
  def index; end
end

app/views/weathers/index.html.erb
<h1>明日の天気検索サイト</h1>

<%= select_tag 'select', options_for_select({
  "札幌": 2128295,
  "青森": 2130658,
  "盛岡": 2111834,
  "仙台": 2111149,
  "秋田": 2113126,
  "山形": 2110556,
  "福島": 2112923,
  "水戸": 2111901,
  "宇都宮": 1849053,
  "前橋": 1857843,
  "埼玉": 6940394,
  "千葉": 2113015,
  "東京": 1850147,
  "横浜": 1848354,
  "新潟": 1855431,
  "富山": 1849876,
  "金沢": 1860243,
  "福井": 1863983,
  "山梨": 1848649,
  "長野": 1856215,
  "岐阜": 1863640,
  "静岡": 1851715,
  "名古屋": 1856057,
  "津": 1849796,
  "大津": 1853574,
  "京都": 1857910,
  "大阪": 1853909,
  "神戸": 1859171,
  "奈良": 1855612,
  "和歌山": 1926004,
  "鳥取": 1849890,
  "松江": 1857550,
  "岡山": 1854383,
  "広島": 1862415,
  "山口": 1848689,
  "徳島": 1850158,
  "高松": 1851100,
  "松山": 1926099,
  "高知": 1859146,
  "福岡": 1863967,
  "佐賀": 1853303,
  "長崎": 1856177,
  "熊本": 1858421,
  "大分": 1854487,
  "宮崎": 1856717,
  "鹿児島": 1860827,
  "那覇": 1856035,
  }, 1),
  id: "wheather-select" %>

<div id="city-name"></div>
<div id="weather"></div>

<%= javascript_pack_tag 'weather' %>
app/javascript/packs/weather.js
// OpenWeatherAPIを使用しています。下記URLからアカウントを作成し、
// APIキー情報を利用してAPI_KEY変数に上書きしてください。
// https://openweathermap.org/

// API_KEYはアカウント登録した際のAPIキーを使用して下さい
const API_KEY = "***"

window.onload = function() {
  weather_search()
};

const wheather_select = document.querySelector('#wheather-select');
const options = document.querySelectorAll("#wheather-select option");
const weather_search = function () {
  const index =  this.selectedIndex;
  const city_id = index ? options[index].value : wheather_select.value
  const url = 'http://api.openweathermap.org/data/2.5/forecast?id=' + city_id + '&appid=' + API_KEY;
  
  fetch(url).then((data) => {
    return data.json();
  }).then((json) => {
    let insertHTML = "";
    let tomorrow = 8
    let weather = document.querySelector('#weather')
    insertHTML += buildHTML(json, tomorrow);
    weather.innerHTML = insertHTML
  }).catch(error => {
    console.error(error);
  });
}

wheather_select.addEventListener('change', weather_search);

function buildHTML(data, i) {
  let Week = new Array("(日)","(月)","(火)","(水)","(木)","(金)","(土)");
  let date = new Date(data.list[i].dt_txt);
  date.setHours(date.getHours() + 3);
  let month = date.getMonth()+1;
  let day = month + "" + date.getDate() + "" + Week[date.getDay()] + date.getHours() + ":00";
  let icon = data.list[i].weather[0].icon;
  let main = weatherJavaneseConversion(data.list[i].weather[0].main)

  let html =
  '<div class="weather-report">' +
    '<h2>明日の天気は'+ main +'です!</h2>' +
    '<img src="http://openweathermap.org/img/w/' + icon + '.png">' +
    '<div class="weather-date">' + day + '</div>' +
  '</div>'
    ;
  return html
}

function weatherJavaneseConversion(name) {
  switch (name) {
    case "Clear":
      return "晴れ"
    case 'Clouds':
      return "曇り"
    case "Rain":
      return ""
    case "Snow":
      return ""
    default:
      console.log(name)
      return name
  }
}

参考

RailsでOpenWeatherMapから天気予報を取得する
【Rails/JS】無料API「OpenWeatherMap」で天気予報を表示する
【Rails】OpenWeatherMapを用いて、登録住所の天気予報を、日本語で表示する方法

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?