LoginSignup
13
20

More than 5 years have passed since last update.

geocoderが便利過ぎる!

Posted at

作っているアプリケーションで住所から座標を使う必要があったので、メモ

今まではgoogle APIを使用して、住所から位置座標を特定して値をとっていたが
gem 'geocoder'を導入するとデータベース保存時に自動で入れてくれる。

geocoderの導入

Gemfile
gem 'geocoder'

あとはbundle install

座標データが欲しいmodelへの記述

model.rb
geocoded_by :住所のカラム名
after_validation :geocode, if: :住所のカラム名_changed?

住所のカラム名には自身のモデルの住所が格納されているカラムを入れてください。
保存したいテーブルにはlatitude,longitudeカラムを作成することを忘れずに!!

実際の保存

住所のカラム名に住所を入れて保存を行えば、自動的にlatitude,longitudeカラムに保存される。
スゴイ!!!

おまけ

model.rb
reverse_geocoded_by :latitude, :longitude
after_validation :reverse_geocode

とすると逆に、座標情報保存時に住所を保存してくれる。

13
20
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
13
20