Skip to content

Instantly share code, notes, and snippets.

@dougalcorn
Created December 23, 2010 18:03
Show Gist options
  • Select an option

  • Save dougalcorn/753314 to your computer and use it in GitHub Desktop.

Select an option

Save dougalcorn/753314 to your computer and use it in GitHub Desktop.
Basic ruby blass with parts of an address that can be assembled into a string and geolocated with Google Maps api
GOOGLE_MAPS_API_KEY = "something"
# This is a plain old ruby class that assumes someone has give it the
# parts of an address. The end goal is to use Google to geolocate it
# and assign a lat/long
class Locateable
attr_accessor :street1, :street2, :city, :state, :country
attr_accessor :latitude, :longitude, :accuracy
# returns false if google was unable to geolocate the
# object. returns an array (and sets the objects accessors) of [lat,
# long, accuracty] if successful.
def geolocate
return false unless city and state and country
begin
if (response = google_locate) !~ /^200/
if (response = google_locate("", city, state, country)) !~ /^200/
if (response = google_locate("", "", state, country)) !~ /^200/
if (response = google_locate("", "", "", country)) !~ /^200/
return false
end
end
end
end
response, self.accuracy, self.lat, self.long = response.split(",")
return false if accuracy == "0"
rescue Timeout::Error
# Google didn't respond, do something to try again later (maybe)
return false
end
[latitude, longitude, accuracy]
end
protected
# Actually assemble the structured address into something google
# searchable and make the http request. You can either pass in all
# the parts of the address, but it defaults to the object's
# attributes if they aren't given
def google_locate(street1 = nil, city = nil, state = nil, country = nil)
if street1
street = street1
else
street = "#{self.street1}, #{street2}"
end
address = "#{street}, #{city || self.city}, #{state || self.state}, #{country || self.country}"
params = "q=" + CGI.escape(address)
params += "&output=csv&key=#{GOOGLE_MAPS_API_KEY}"
url = URI.parse("http://maps.google.com/maps/geo?#{params}")
timeout(5) do
Net::HTTP.get(url)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment