Created
June 15, 2010 02:30
-
-
Save zgchurch/438621 to your computer and use it in GitHub Desktop.
Google maps geolocation API with activerecord
This file contains 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 '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