Geocode the model

suggest change

Suppose, your users and/or groups have profiles and you want to display address profile fields on a google map.

# app/models/profile_fields/address.rb
class ProfileFields::Address < ProfileFields::Base
  # Attributes: 
  # label, e.g. "Work address"
  # value, e.g. "Willy-Brandt-Straße 1\n10557 Berlin"
end

A great way to geocode the addresses, i.e. provide longitude and latitude is the geocoder gem.

Add geocoder to your Gemfile and run bundle to install it.

# Gemfile
gem 'geocoder', '~> 1.3'

Add database columns for latitude and longitude in order to save the location in the database. This is more efficient than querying the geocoding service every time you need the location. It’s faster and you’re not hitting the query limit so quickly.

bin/rails generate migration add_latitude_and_longitude_to_profile_fields \
    latitude:float longitude:float
bin/rails db:migrate  # Rails 5, or:
rake db:migrate       # Rails 3, 4

Add the geocoding mechanism to your model. In this example, the address string is stored in the value attribute. Geocode when the record has changed, and only when a value is present:

# app/models/profile_fields/address.rb
class ProfileFields::Address < ProfileFields::Base
  geocoded_by :value
  after_validation :geocode, if: ->(address_field){ 
    address_field.value.present? and address_field.value_changed? 
  }

end

In the 1.3 series, geocoder uses Google as the lookup service by default. Current Google geocoding also requires an API key. The gem can calculate distance and search by proximity. For more information, see the geocoder README.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents