Created
January 17, 2012 17:35
-
-
Save matthutchinson/1627728 to your computer and use it in GitHub Desktop.
Simple Google v3 API Geocoder in Ruby
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
#!/usr/bin/ruby | |
require 'rubygems' | |
require 'net/http' | |
require 'net/https' | |
require 'uri' | |
require 'json' | |
class GoogleGeocoder | |
BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json' | |
def locate(options = {}) | |
parse_response(do_request(options)) | |
end | |
protected | |
def do_request(options = {}) | |
params = options.merge(:sensor => false) | |
if params[:latlng] | |
params.delete(:address) | |
elsif params[:address] | |
params.delete(:latlng) | |
params.merge(:address => URI.encode(params[:address])) | |
else | |
raise "Please supply an address or latlng" | |
end | |
uri = URI.parse("#{BASE_URL}?#{params.collect { |k,v| "#{k}=#{URI.encode(v.to_s)}" }.reverse.join('&')}") | |
http = Net::HTTP.new(uri.host, 80) | |
request = Net::HTTP::Get.new(uri.to_s) | |
http.request(request).body | |
end | |
def parse_response(response) | |
location_data = JSON.parse(response) | |
raise "Invalid response" unless location_data.kind_of?(Hash) | |
raise "API returned error!" if location_data['error'] | |
raise "Status is not OK" unless(location_data['status'] == 'OK') | |
raise "No Location results found" unless(location_data['results'].length > 0) | |
location_data['results'] | |
end | |
end | |
# use address, or reverse geocode by providing a latlng | |
brittany = { :latlng => '48.22625415988,-3.263935462275' } # brittany | |
vegas = { :latlng => '28.1333333,-16.5333333' } # vegas | |
paris = { :address => 'Paris' } # Paris | |
gg = GoogleGeocoder.new | |
puts gg.locate(vegas).inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment