Class: Google4R::Maps::Geocoder

Inherits:
Object
  • Object
show all
Defined in:
lib/google4r/maps.rb

Overview

Allows to geocode a location.

Uses the Google Maps API to find information about locations specified by strings. You need a Google Maps API key to use the Geocoder.

The result has the same format as documented in [1] (within <kml>) if it is directly converted into Ruby: A value consisting of nested Hashes and Arrays.

After querying, you can access the last server response code using #last_status_code.

Notice that you can also use Google’s geolocator service to locate ZIPs by querying for the ZIP and country name.

Usage Example:

api_key = 'abcdefg'
geocoder = Google4R::Geocoder.new(api_key)
result = geocoder.query("1 Infinite Loop, Cupertino")
puts result["Placemark"][0]["address"] # => "1 Infinite Loop, Cupertino, CA 95014"
1

www.google.de/apis/maps/documentation/#Geocoding_Structured

Constant Summary collapse

GET_URL =

The hardcoded URL of Google’s geolocator API.

'http://maps.google.com/maps/geo?q=%s&output=%s&key=%s'.freeze
G_GEO_SUCCESS =

Response code constants.

200
G_GEO_SERVER_ERROR =
500
G_GEO_MISSING_ADDRESS =
601
G_GEO_UNKNOWN_ADDRESS =
602
G_UNAVAILABLE_ADDRESS =
603
G_GEO_BAD_KEY =
610

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Geocoder

Creates a new Geocoder object. You have to supply a valid Google Maps API key.



82
83
84
# File 'lib/google4r/maps.rb', line 82

def initialize(key)
  @api_key = key
end

Instance Attribute Details

#last_status_codeObject (readonly)

Returns the last status code returned by the server.



67
68
69
# File 'lib/google4r/maps.rb', line 67

def last_status_code
  @last_status_code
end

Instance Method Details

#query(query) ⇒ Object

Parameters

query

The place to locate.

Exceptions

Throws a KeyException if the key for this Geocoder instance is invalid and throws a ConnectionException if the Geocoder instance could not connect to Google’s server or an server error occured.

Return Values

Returns data in the same format as documented in [1]

Example of returned values:

{
  "name": "1600 Amphitheatre Parkway, Mountain View, CA, USA",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [
    {
      "address": "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
      "AddressDetails": {
        "Country": {
          "CountryNameCode": "US",
          "AdministrativeArea": {
            "AdministrativeAreaName": "CA",
            "SubAdministrativeArea": {
              "SubAdministrativeAreaName": "Santa Clara",
              "Locality": {
                "LocalityName": "Mountain View",
                "Thoroughfare": {
                  "ThoroughfareName": "1600 Amphitheatre Pkwy"
                },
                "PostalCode": {
                  "PostalCodeNumber": "94043"
                }
              }
            }
          }
        },
        "Accuracy": 8
      },
      "Point": {
        "coordinates": [-122.083739, 37.423021, 0]
      }
    }
  ]
}
1

www.google.de/apis/maps/documentation/#Geocoding_Structured

Raises:



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/google4r/maps.rb', line 140

def query(query)
  # Check that a Google Maps key has been specified.
  raise KeyException.new("Cannot use Google geocoder without an API key.") if @api_key.nil?

  # Compute the URL to send a GET query to.
  url = URI.escape(GET_URL % [ query, 'json', @api_key.to_s ])

  # Perform the query via HTTP.
  response = 
    begin
      Net::HTTP.get_response(URI.parse(url))
    rescue Exception => e
      raise ConnectionException.new("Could not connect to '#{url}': #{e.message}")
    end
  body = response.body

  # Parse the response JSON.
  result = JSON.parse(body)
  
  @last_status_code = result['Status']['code']

  # Check that the query was successful.
  if @last_status_code == G_GEO_BAD_KEY then
    raise KeyException.new("Invalid API key: '#{@api_key}'.")
  elsif @last_status_code == G_GEO_SERVER_ERROR then
    raise ConnectionException.new("There was an error when connecting to the server. Result code was: #{status}.") 
  elsif @last_status_code == G_GEO_UNKNOWN_ADDRESS then
    return nil
  end

  return result
end