25
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでgeocoderをつかって住所から緯度経度を登録する

Last updated at Posted at 2015-02-20

GoogleMap用途などで、住所を属性に持つモデルに対して緯度・経度を登録する場合はgeocoderが便利です。

geocoder

geocoderは住所⇔緯度・経度を取得・登録できるスグレモノです。

geocoder のインストール

Gemfile
# geocoder
gem 'geocoder'

Gemfileに追記したら、 bundle install でGemをインストールします

モデルの修正

Ex. Hotelモデルに住所(address), 緯度(latitude), 経度(longitude)がある場合

hotel.rb に以下のコードを記述するだけです。

hotel.rb
geocoded_by :address
after_validation :geocode, if: lambda {|obj| obj.address_changed?}

これで、モデル登録時と住所(address)変更時にgeocoderが動いて緯度・経度のデータが登録・更新されます :smiley:


参考

25
26
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
25
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?