Rails – Implementation of Geocoder on Model

Previous related post: Rails – Find Location using Geocoder

Implementation of Geocoder on Model is simple and straight forward. What we need is just adding two more columns on the Model table for storing the coordinates(Latitude & Longitude) and one column for storing the address.

1. Add latitude, longitude and address to the User model

  • rails generate migration AddLatitudeAndLongitudeAndAddressToUser latitude:float longitude:float address:string

 

2. Run the migration

  • rake db:migrate

 

3. Add the following lines in app/model/user.rb

geocoded_by :address
after_validation :geocode

 

4. Try how Geocoder works in Rails Console

# Get the first user
user = User.first

# Set the user address field
user.address = "Hong Kong"

# Generate the user latitude and longitude
user.geocode

# Check the user latitude and longitude
user.latitude.to_s + " " + user.longitude.to_s

 

Here is an example which i changed the user address from Hong Kong to Taiwan. Notice that the latitude and longitude are changed also.

 

Done =)

Reference: GitHub – alexreisner / geocoder

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.