2
1

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】Google Mapの表示

Posted at

#はじめに
Ruby on Rails で ユーザーが入力した住所から、経度と緯度を取得して、Google Map を表示する方法。

#開発環境
・Ruby: 2.6.6
・Rails: 5.2.6
・Windows10

#APIキーの取得
Google Map Platformにアクセスし、Google Mapを表示させるためのAPIキーを取得。
取得方法はこちら↓の記事を参考に。
https://qiita.com/tiara/items/4a1c98418917a0e74cbb

#アプリの作成
Ⅰ.Google Mapを表示させるための簡単なアプリを作成します。

$rails new Map_application

Ⅱ.Gemgfileにgeocoderを追加
今回、住所・緯度・経度のカラムを持つmodelを作成するが、ユーザーが住所を入力すれば緯度・経度が自動的に取得され、Google Mapが表示されるようにする。

Gemfile
gem 'geocoder'
$bundle

Ⅲ.modelの作成
名前、住所、緯度、経度のカラムをもつmodel(Map)を作成。

$rails g model Map name:text address:text latitude:float longitude:float
$rails db:migrate

また、Map.rbに下記のように記載すると、geocoder が address から経度・緯度を取得してくれます。

Map.rb
class Map < ApplicationRecord
    geocoded_by :address
    after_validation :geocode, if: :address_changed?
end

Ⅳ.controllerの作成

rails g controller maps index new show
maps.controller.rb
class MapsController < ApplicationController

  def index
    @maps=Map.all
  end

  def new
    @map=Map.new
  end

  def show
    @map=Map.find_by(id:params[:id])
  end

  def create
    @map=Map.new(map_params)
    if @map.save
      redirect_to maps_path
    else
      render action: :new
    end
  end

  def map_params
    params.require(:map).permit(:name, :address, :latitude, :longitude)
  end

end

routeも編集

routes.rb
Rails.application.routes.draw do
  resources :maps
end

Ⅴ. geocorder.rb作成
config/initializeの中にgeocorder.rbを作成

作成したら以下を書き足す。

config/initialize/geocorder.rb
Geocoder.configure(
  # Geocoding options
 
  # street address geocoding service (default :nominatim)
  lookup: :google,

  # to use an API key:
  api_key: "APIKEY",

  # geocoding service request timeout, in seconds (default 3):
  timeout: 5,

  # set default units to kilometers:
  units: :km
)

Ⅵ. viewsを編集

new.html.erb
<%= form_for @map do |f| %>
    <div class="field">
    <%= f.label :name, "場所", class: "label" %>
    <%= f.text_field :name, class: "input" %>
    </div>

    <div class="field">
    <%= f.label :address, "住所", class: "label" %>
    <%= f.text_area :address, class: "input" %>
    </div>

    <%= f.submit '投稿', class: "button is-success" %>
<% end %>
show.html.erb
<div class="content">
   <div id="map"></div>
</div>
           
<script type="text/javascript">
    function initMap() {

        var test ={lat: <%= @map.latitude %>, lng: <%= @map.longitude %>};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 15,
            center: test
        });
        var transitLayer = new google.maps.TransitLayer();
        transitLayer.setMap(map);

        var contentString = '住所:<%= @map.address %>';
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position:test,
            map: map,
            title: contentString
        });

        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
    }
</script>

<script async defer
        src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyAafClNH0jxMHeNSabrL4onyejsurfeRm8&callback=initMap">
</script>

<style type="text/css">
  #map { height: 200px;
    margin-left:auto;
    margin-right:auto;
    text-align:left;
    width: 30%;}
</style>

Ⅶ. Google Mapが表示されるか確認
新規登録画面で投稿↓
image.png

http://localhost:3000/maps/1
に遷移すると無事表示されていれば成功。

image.png

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?