Class: GoogleGeocode

Inherits:
RCRest
  • Object
show all
Defined in:
lib/google_geocode.rb

Overview

Library for looking up coordinates with Google’s Geocoding API.

www.google.com/apis/maps/documentation/#Geocoding_HTTP_Request

Defined Under Namespace

Classes: AddressError, Error, KeyError, Location

Constant Summary collapse

VERSION =

This is the version you are running.

'1.2.1'

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ GoogleGeocode

Creates a new GoogleGeocode that will use Google Maps API key key. You can sign up for an API key here:

www.google.com/apis/maps/signup.html



42
43
44
45
# File 'lib/google_geocode.rb', line 42

def initialize(key)
  @key = key
  @url = URI.parse 'http://maps.google.com/maps/'
end

Instance Method Details

#check_error(xml) ⇒ Object

Extracts and raises an error from xml, if any.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/google_geocode.rb', line 71

def check_error(xml)
  status = xml.elements['/kml/Response/Status/code'].text.to_i
  case status
  when 200 then # ignore, ok
  when 500 then
    raise Error, 'server error'
  when 601 then
    raise AddressError, 'missing address'
  when 602 then
    raise AddressError, 'unknown address'
  when 603 then
    raise AddressError, 'unavailable address'
  when 610 then
    raise KeyError, 'invalid key'
  when 620 then
    raise KeyError, 'too many queries'
  else
    raise Error, "unknown error #{status}"
  end
end

#locate(address) ⇒ Object

Locates address returning a Location struct.



50
51
52
# File 'lib/google_geocode.rb', line 50

def locate(address)
  get :geo, :q => address
end

#make_url(method, params) ⇒ Object

Creates a URL from the Hash params. Automatically adds the key and sets the output type to ‘xml’.



96
97
98
99
100
101
# File 'lib/google_geocode.rb', line 96

def make_url(method, params)
  params[:key] = @key
  params[:output] = 'xml'

  super method, params
end

#parse_response(xml) ⇒ Object

Extracts a Location from xml.



57
58
59
60
61
62
63
64
65
66
# File 'lib/google_geocode.rb', line 57

def parse_response(xml)
  l = Location.new

  l.address   = xml.elements['/kml/Response/Placemark/address'].text

  coordinates = xml.elements['/kml/Response/Placemark/Point/coordinates'].text
  l.longitude, l.latitude, = coordinates.split(',').map { |v| v.to_f }

  return l
end