6
4

More than 3 years have passed since last update.

Rails gem 'geocoder'を使って入力した住所をGoogleMapに表示させる

Last updated at Posted at 2020-06-15

「東京都千代田区」のような住所であれば緯度経度を取得してGoogleMapに表示されるが、「東京都千代田区丸の内2-4-1」のように番地まで指定すると、緯度経度を取得できずにマップが表示されなかったが解決できたので投稿。

前準備

・googlemapを使用するためにまずはAPIを取得する。APIの取得はこちらを(https://qiita.com/nagaseToya/items/e49977efb686ed05eadb)

・住所を保存するカラム、緯度経度を保存するカラムを作成。
latitude・longitudeが緯度経度。

schema.rb
create_table "tours", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "address", null: false
    t.float "latitude"
    t.float "longitude"
  end

登場するファイル

・Gemfile
・tour.rb
・.gitignore
・.env
・geocorder.rb
・show.html.erb

Gemfile

geocorderをbundle install

gem 'geocoder'

tour.rb

以下を書き加える

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

geocoded_byが入力した住所から緯度経度を保存。
after_validation :geocodeは後に住所変更があっても、変更後の緯度経度を保存してくれる。

.gitignore ・ .env

.envを.gitignoreに追加。これでgithub上に上がらない。

/.env

.envに以下を書き足す。YOUR_API_KEYの部分を取得したAPIキーにする。

GOOGLEMAP=YOUR_API_KEY

geocorder.rb

rails g geocoder:configでconfig/initialize/geocorder.rbを作成し、以下を書き足す。
api_keyの部分に取得したAPIが入る。

geocorder.rb
Geocoder.configure(
  lookup: :google,
  always_raise: [
    Geocoder::OverQueryLimitError,
    Geocoder::RequestDenied,
    Geocoder::InvalidRequest,
    Geocoder::InvalidApiKey
  ],
  api_key:  ENV['GOOGLEMAP'] ,
  use_https: true
)

show.html.erb

最後にshow.html.erbにgooglemapを貼り付け

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

あとは大きさの好みによって、heightやwidthを調整すればいい。

6
4
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
6
4