Skip to content

Instantly share code, notes, and snippets.

@zgchurch
Created June 15, 2010 02:30
Show Gist options
  • Save zgchurch/438621 to your computer and use it in GitHub Desktop.
Save zgchurch/438621 to your computer and use it in GitHub Desktop.
Google maps geolocation API with activerecord
require 'json'
require 'cgi'
require 'httparty'
module GMap
module Location
def latitude
read_attribute(:latitude) || fetch_coordinates_from_address.latitude
end
def longitude
read_attribute(:longitude) || fetch_coordinates_from_address.latitude
end
def fetch_coordinates_from_address
result = HTTParty.get("http://maps.google.com/maps/api/geocode/json?address=#{CGI::escape(address)}&sensor=false")['results'].first
coordinates = result['geometry']['location']
self.latitude = coordinates['lat']
self.longitude = coordinates['lng']
self
end
end
end
class Place < ActiveRecord::Base
include GMap::Location # assumes address, latitude, and longitude attributes
before_create :fetch_coordinates_from_address, :if => :address
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment