LoginSignup
0
1

More than 3 years have passed since last update.

AIRBNBのようにGOOGLEMAPをWEBに追加

Posted at

追加背景

今自分で習いながらAIRBNBのような民泊シェアリングエコノミーサイトを作っているので、その中でもGOOGLEMAPの位置表示機能を追加する手順をシェアできればかと思います。今回は部屋の掲載ページに載せるので主にROOM関連のファイルで編集していきます。

GEM追加

Gemfile.
gem 'geocoder', '~> 1.4'

bundle install

DB migration

rails g migration AddFieldsToRoom latitude:float longitude: float (掲載した部屋のページに表示したいのでこの場合ROOMのDBに追加)
rails db: migrate

rooms table

Column Type Options
home_type string null: false
room_type string null: false
accommodate integer null: false
bed_room integer null: false
bath_room integer null: false
listing_name string null: false
summary text null: false
address text null: false
is_tv boolean null: false
is_kitchen boolean null: false
is_aircon boolean null: false
is_heating boolean null: false
is_internet boolean null: false
price integer null: false
active boolean null: false
latitude float null: false
longitude float null: false
user references foreign_key: true

Association

  • belongs_to: user
  • has_many: photos

Roomモデルファイル編集

room.rb
  geocoded_by :address
  after_validation :geocode, if: :address_changed?

ROOMのDBのADDRESSから位置付けをする。あとはアドレスがアップデートされる度にGEOCODEがVALIDATIONをかけ、位置経緯を自動的に決める。

Roomビューファイル編集

rooms/show.html.rb
    <!-- GOOGLE MAP -->
    <div class="row">

      <div id="map" style="width: 100%; height: 400px"></div>

      <script src="https://maps.googleapis.com/maps/api/js"></script>
      <script>
          function initialize() {
            var location = {lat: <%= @room.latitude %>, lng: <%= @room.longitude %>};
            var map = new google.maps.Map(document.getElementById('map'), {
              center: location,
              zoom: 14
            });

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

            var infoWindow = new google.maps.InfoWindow({
              content: '<div id="content"><%= image_tag @room.cover_photo(:medium) %></div>'
            });
            infoWindow.open(map, marker);
          }

          google.maps.event.addDomListener(window, 'load', initialize);
      </script>

最後の一行はGOOGLEMAP APIのマップ生成を行うためのJquery
https://techacademy.jp/magazine/5638#sec2 (DOMについて忘れたかけてるのでもう一度復習)

Markerはマップ上にピンマークされるように指定。
infowindowでは部屋のカバー写真をマップ上に表示させる

これでマップは表示されるはず。(下の図を参照、場所は適当にマレーシアにしてます笑)
image.png

DBではちゃんと経緯を生成されている!
image.png

そして。。。表示成功!勉強しながらやっていますが、レベルアップしたような達成感はあります。(ズームアウトすると訳のわからん熱帯雨林みたいなところにある、ちょうど写真には合うけど笑)
image.png

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