Ruby on Rails Using GoogleMaps with Rails Geocode the model


Example

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. Configure the geocoding to perform when the record has changed, and only whan 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

By default, geocoder uses google as lookup service. It has lots of interesting features like distance calculations or proximity search. Fore more information, have a look at the geocoder README.