LoginSignup
12
16

More than 5 years have passed since last update.

railsで、住所入れたら、その位置のgooglemapを表示させる

Posted at

やりたいこと

screenshot.png

京都駅と記入して、青いボタンの登録をすると、下に京都駅のgoogle mapが出てくる。

gem追加

Gemfile
gem 'geocoder'
ターミナル
bundle install

モデル説明

今回は、shopモデルに住所を入れたいとする

shopモデル 

screenshot.png

上の図の説明は、shopモデルである。店の名前と来客人数のカラムを作ってある。
  googlemap表示のために、カラムaddress latitude longtudeを追加する。

ターミナル
rails generate migration AddaddressLatitudeAndLongitudeToShop address:string latitude:float longitude:float
shop.rb
geocoded_by :address
after_validation :geocode, if: :address_changed? 

上の記述で、 住所(カラムaddress)を入れたときに、自動でその住所の緯度、経度をカラムlatitude,
longitudeに記述してくれる。

登録画面

show.html.erb
<%= form_for @shop :url => {:action => :update}   do |f| %>

 <div class="text-center"><%= f.text_field :address %></div>

    <%= f.submit "住所登録", class: "btn btn-primary center-block" %>


 <% end %>


 <body>
    <div id="map"></div>
    <style>
        #map {
        height: 500px;
        width: 70%;
      }
    </style>
    <script>
      function initMap() {
        var uluru = {lat: <%= @shop.latitude %>, lng: <%= @shop.longitude %>};
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 16,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>
  </body>

下からの3行目YOUR_API_KEY記述がある。 これは、各自でgooglemapAPIからkey取得する必要がある。
http://qiita.com/kitaokeita/items/a7f33615940e67c13820
このリンクにkey取得のやり方が書かれているので参考してください

参考文献
https://dev.9bar.tokyo/rails/geocoder

12
16
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
12
16