LoginSignup
31
36

More than 5 years have passed since last update.

Railsで住所からGoogleMapを表示する。しかも5分で。

Posted at

前提

  • 住所(addressとする)を持つモデルがすでにある(Userとする)
  • 住所を更新することができる
  • asset pipeline使わない

gemをいれる

gem "gmaps4rails"
gem "geocoder"
bundle install

migration

緯度経度を保存するカラム追加

rails g migration AddLatitudeAndLongitudeToUsers latitude:float longitude:float

rails db:migrate

JS

rails g gmaps4rails:copy_js
header.haml

%script(src="//maps.google.com/maps/api/js?v=3.23")
%script(src="//cdn.rawgit.com/mahnunchik/markerclustererplus/master/dist/markerclusterer.min.js")
%script(src='//cdn.rawgit.com/printercu/google-maps-utility-library-v3-read-only/master/infobox/src/infobox_packed.js' type='text/javascript')
%script(src='/javascripts/gmaps_google.js')

Model

address 部分は住所や駅名等のカラムを指定する。

geocoded_by :address
after_validation :geocode

View

Mapが表示されるところ。サイズはご自由に。指定しないと何もでない。

表示したいとこ.haml
%div(style="width: 100%;" )
  #map(style="height: 200px;" )

google.maps.LatLng の部分で緯度経度を渡している。

:javascript
  handler = Gmaps.build('Google');
  handler.buildMap({
    provider: {
      zoom: 12,
      center:    new google.maps.LatLng(#{@user.latitude}, #{@user.longitude}),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    },
    internal: {id: 'map'}}, function(){
    handler.fitMapToBounds();
  });

はい!!ここまでで5分!!

やってみる

Screen Shot 2016-09-14 at 16.18.24.png

Screen Shot 2016-09-14 at 16.18.39.png

でましたー。

まとめ

住所や駅名を保存するタイミングでGeocodingを行い緯度経度を取得&保存を勝手にやってくれる。とても便利。

31
36
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
31
36