Skip to content

Instantly share code, notes, and snippets.

@kdonovan
Created September 26, 2011 11:07
Show Gist options
  • Save kdonovan/1242018 to your computer and use it in GitHub Desktop.
Save kdonovan/1242018 to your computer and use it in GitHub Desktop.
Example using precision from geokit gem to ensure geocoding is sane
class SomeModel < ActiveRecord::Base
validate :geocode_address
def address
[street_address, city, state, zip].select{|a| !a.blank?}.join(', ')
end
# ...
protected
def geocode_address
return true unless new_record? || street_address_changed? || city_changed? || state_changed? || zip_changed?
return true if address.blank?
geo = Geokit::Geocoders::MultiGeocoder.geocode(address)
if geo.success && geo.accuracy.to_i > 3 # Ensure better than county-level precision (http://code.google.com/apis/maps/documentation/geocoding/v2/index.html#GeocodingAccuracy)
self.latitude, self.longitude = geo.lat, geo.lng
self.street_address, self.city, self.state, self.zip = geo.street_address, geo.city, geo.state, geo.zip
else
errors.add_to_base("Unable to geocode address -- please be sure you entered it correctly")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment