Dragon Arrow written by Tatsuya Nakaji, all rights reserved animated-dragon-image-0164

gem geocoder で 地名と座標を自由に変換

updated on 2019-07-26

rails で住所から緯度経度を取得


***クライアント側は2018年の夏頃までは設定しなくても動いてたんですが、現在はgoogleのgeocodingAPIを有効化しないと使えないので、急に使えなくなっていてびっくりした方も多いと思います!!自分もその1人です!!

Geocoding API

1. GeocodingAPI を有効化してAPIキーを作成

GoogleDevelopersからGeocoding APIを有効化し、認証情報を作成してAPIキー作成(すでにAPIを持っている場合は新たに作る必要はない)

Geocoder

1. gemのインストール

Gemfile
...
gem 'geocoder'
$ bundle install



2. geocoder設定ファイルを作成、編集

$ rails generate geocoder:config (設定ファイルがconfig/initializers/geocoder.rbとしてできる)
config/initializers/geocoder.rb
Geocoder.configure(
# Geocoding options
# timeout: 3,                 # geocoding service timeout (secs)
# lookup: :google,            # name of geocoding service (symbol)
# ip_lookup: :ipinfo_io,      # name of IP address geocoding service (symbol)
language: :ja,                # :enから:jaに変えた
# use_https: false,           # use HTTPS for lookup requests? (if supported)
# http_proxy: nil,            # HTTP proxy server (user:pass@host:port)
# https_proxy: nil,           # HTTPS proxy server (user:pass@host:port)
api_key: "あなたのAPI_KEY",               # APIキーを設定しないと動きません
# cache: nil,                 # cache object (must respond to #[], #[]=, and #del)
# cache_prefix: 'geocoder:',  # prefix (string) to use for all cache keys
# Exceptions that should not be rescued by default
# (if you want to implement custom error handling);
# supports SocketError and Timeout::Error
# always_raise: [],
# Calculation options
# units: :mi,                 # :km for kilometers or :mi for miles 1mi=1.6km
# distances: :linear          # :spherical or :linear
)


2. Modelにフィールドを作成

$ rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float address:string
$ rake db:migrate
moder.rb
geocoded_by :address # addressカラムにジオコーディングを実装
after_validation :geocode, :if => :address_changed? # addressカラムが変更(保存や更新)されたらジオコーディングが行われる


3. Viewを作成

<%= form_for @listing do |f| %>

<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>住所</label>
<%= f.text_field :address, placeholder: "例: 東京都港区六本木6丁目11−1", class: "form-control",
required: "true" %>
</div>
</div>
</div>

<div class="actions">
<%= f.submit "更新", class: "btn btn-danger" %>
</div>
<% end %>