Created
October 25, 2008 20:58
-
-
Save cpetersen/19781 to your computer and use it in GitHub Desktop.
Datamapper Location object that updates logitude, latitude, city and state based on zip code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'hpricot' | |
require 'open-uri' | |
class Location | |
include DataMapper::Resource | |
before :create, :update_location | |
property :id, Serial | |
property :name, String | |
property :email, String | |
property :city, String | |
property :state, String | |
property :zip_code, String | |
property :longitude, Float | |
property :latitude, Float | |
def coordinates=(value) | |
self.longitude, self.latitude = value.split(",") | |
end | |
def coordinates | |
"#{self.longitude},#{self.latitude}" | |
end | |
def self.google_maps_key | |
# YOUR GOOGLE MAPS ID HERE | |
end | |
protected | |
def update_location | |
doc = Hpricot.parse(open("http://maps.google.com/maps/geo?q=#{self.zip_code}&output=xml&key=#{Location.google_maps_key}")) | |
self.city = (doc/:localityname)[0].inner_text | |
self.state = (doc/:administrativeareaname)[0].inner_text | |
self.coordinates = (doc/:coordinates)[0].inner_text | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment