[RUBY] [Rails] How to display the weather forecast of the registered address in Japanese using OpenWeatherMap

Target

ezgif.com-video-to-gif.gif

Development environment

・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina

Premise

The following has been implemented.

Slim introduction -Login function implementation

Get API key

1. Access the link below

OpenWeatherMap

2. Click Sign in

スクリーンショット 2020-06-10 19.37.06.png

3. Click Create an Account.

スクリーンショット 2020-06-10 19.37.16.png

4. Enter the required information and click Create Acount

スクリーンショット 2020-06-10 19.38.07.png

5. Set Purpose to ʻother(appropriate) and clickSave`

スクリーンショット 2020-06-10 19.39.57.png

6. Click ʻAPI keys`

スクリーンショット 2020-06-10 19.40.13.png

7. Copy Key

スクリーンショット 2020-06-10 19.40.40.png

8. Make API key an environment variable

Implement in the same way as "API key is made into environment variable" in the following article.

Google Map display

Implementation

1. Add column

Terminal


$ rails g migration AddPrefectureToUsers prefecture:string

~_add_prefecture_to_users.rb


class AddPrefectureToUsers < ActiveRecord::Migration[5.2]
  def change
    add_column :users, :prefecture, :string
  end
end

Terminal


$ rails db:migrate

2. Edit ʻapplication_controller.rb`

Add prefecture to the strong parameter.

applocation_controller.rb


def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:email, :name, :prefecture])
end

3. Edit the view

slim:users/show.html.slim


h3.weather-text
  = @user.prefecture

#weather

javascript:

  $(function () {
    var API_KEY = "#{ENV['OPEN_WEATHER_MAP_API']}"; //API key(Environment variable)To a variable
    var city = "#{@user.prefecture}"; //Substitute the prefecture name of the user in the variable
    //Assign API to read variable
    var url = 'https://api.openweathermap.org/data/2.5/forecast?q=' + city + ',jp&units=metric&APPID=' + API_KEY;

    $.ajax({
        url: url,
        dataType: 'json',
        type: 'GET',
      })
      .done(function (data) {
        var insertHTML = '';
        var cityName = data.city.name;
        $('#city-name').html(cityName);

        //By default, it gets the weather every 3 hours, so
        //Get the weather every 24 hours by getting the data in multiples of 8
        for (var i = 0; i <= 32; i = i + 8) {
          insertHTML += buildHTML(data, i);
        }
        $('#weather').html(insertHTML);
      })
      .fail(function (data) {
        alert('Failed to get the weather forecast');
      });
  });

  //Localizing into Japanese
  function buildHTML(data, i) {
    var Week = new Array('(Day)', '(Month)', '(fire)', '(water)', '(wood)', '(Money)', '(soil)');
    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()];
    var icon = data.list[i].weather[0].icon;
    var html =
      '<div class="weather-report">' +
        '<img src="https://openweathermap.org/img/w/' + icon + '.png ">' +
        '<span class="weather-date">' + day + "</span>" +
        '<div class="weather-temp-max">' + 'Best:' + Math.round(data.list[i].main.temp_max) + "℃</div>" +
        '<span class="weather-temp-min">' + 'Minimum:' + Math.floor(data.list[i].main.temp_min) + "℃</span>" +
      '</div>';
    return html
  }

Recommended Posts

[Rails] How to display the weather forecast of the registered address in Japanese using OpenWeatherMap
How to set the display time to Japan time in Rails
[Rails] How to display an image in the view
[Rails] How to write in Japanese
Display weather forecast using OpenWeatherMap, an external API in Ruby
[Java] How to display the day of the week acquired by LocalDate, DateTimeformatter in Japanese
[Rails] How to display information stored in the database in view
[Rails] How to omit the display of the character string of the link_to method
[Rails 5] How to display the password change screen when using devise
Get weather forecast from OpenWeatherMap in Rails
How to display error messages in Japanese
How to display the text entered in text_area in Rails with line breaks
[Ruby On Rails] How to search the contents of params using include?
How to translate Rails into Japanese in general
How to use JQuery in js.erb of Rails6
How to check Rails commands in the terminal
[Rails] How to convert UC time display to Japanese time display
[Ruby on Rails] How to write enum in Japanese
[Rails, JS] How to implement asynchronous display of comments
[Rails] How to change the column name of the table
[Rails] How to get the contents of strong parameters
How to install Docker in the local environment of an existing Rails application [Rails 6 / MySQL 8]
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
[Rails] I want to display the link destination of link_to in a separate tab
[Swift] How to display the entered characters in Widget via UserDefaults when using WidgetKit
How to display the select field of time_select every 30 minutes
How to deploy jQuery in your Rails app using Webpacker
How to display a graph in Ruby on Rails (LazyHighChart)
Let's summarize how to extend the expiration date of Rails
How to implement one-line display of TextView in Android development
How to derive the last day of the month in Java
[Rails] Where to be careful in the description of validation
[Rails] How to convert the URI of the image sent by http to https when using Twitter API
[Rails / Routing] How to refer to the controller in the directory you created
[Rails] How to get the URL of the transition source and redirect
[rails] How to display db information
How to set the IP address and host name of CentOS8
[Webpacker] Summary of how to install Bootstrap and jQuery in Rails 6.0
[rails] How to display parent information in child view in nested relationships
How to display 0 on the left side of the standard input value
[Rails / Heroku / MySQL] How to reset the DB of Rails application on Heroku
How to get the contents of Map using for statement Memorandum
[Rails] How to change the page title of the browser for each page
How to delete large amounts of data in Rails and concerns
How to get the id of PRIMAY KEY auto_incremented in MyBatis
[Behavior confirmed in December 2020] How to implement the alert display function
How to solve the unknown error when using slf4j in Java
[Rails] Creation of the second vertical axis and Japanese localization in graph drawing using amCharts4, etc.
Method definition location Summary of how to check When defined in the project and Rails / Gem
[Rails] How to reset the database in production environment (Capistrano version)
How to get the length of an audio file in java
How to increment the value of Map in one line in Java
How to write the view when Vue is introduced in Rails?
[rails6.0.0] How to save images using Active Storage in wizard format
How to install Swiper in Rails
[Ruby on Rails] How to log in with only your name and password using the gem devise
How to set an image in the drawable Left / Right of a button using an icon font (Iconics)
[Ruby on Rails] When logging in for the first time ・ How to split the screen in half using jQuery
How to set the indent to 2 single-byte spaces in the JAXB implementation of the JDK
How to decorate the radio button of rails6 form_with (helper) with CSS
How to implement a slideshow using slick in Rails (one by one & multiple by one)