Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

前提

  • 住所(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を行い緯度経度を取得&保存を勝手にやってくれる。とても便利。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away