LoginSignup
4
3

More than 5 years have passed since last update.

Railsで位置情報を取得したい時にやったことのメモ

Last updated at Posted at 2017-12-31

elasticsearhで位置情報検索をさせようと思い、緯度経度の情報をどうやって取得しようかと考えていたのだが、結局geocoderを使うことにした。

これだとaddressってattributeがあると自動でlatitudeとlongitudeってカラムに緯度経度が入る。

設定

例えばテーブルの定義をこんな感じにしていく

 create_table "Places", force: true, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC" do |t|
   t.string   "address",     limit: 80, null: false
   t.float    "latitude",               null: false
   t.float    "longitude",              null: false
   t.datetime "created_at"
   t.datetime "updated_at"
 end

そしてmodelに以下のコードを追加

app/modles/place.rb
class Place < ApplicationRecord
  geocoded_by :address
  after_validation :geocode, if: ->(obj) { obj.address.present? and obj.address_changed? }
end

これで以下のようにaddressをセットすると緯度経度が自動でセットされる。

実験

place = Place.create('横浜市青葉区')

> place
#<Place:0x007f85d74a5588
 id: 1,
 address: "横浜市青葉区",
 latitude: 35.55282400000001,
 longitude: 139.5370189,
 created_at: Mon, 01 Jan 2018 00:30:34 JST +09:00,
 updated_at: Mon, 01 Jan 2018 00:30:34 JST +09:00>

便利だ。これをElasticsearchに突っ込めば、これを使って位置情報の検索できる!!

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