Class: GoogleMaps::Services::Geocode

Inherits:
Object
  • Object
show all
Defined in:
lib/googlemaps/services/geocoding.rb

Overview

Performs requests to the Google Maps Geocoding API.

Examples:

geocode = GoogleMaps::Services::Geocode.new(client)
result = geocode.query(address: "1600 Amphitheatre Parkway, Mountain View, CA")

Since:

  • 1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Geocode

Returns a new instance of Geocode.

Since:

  • 1.0.0



16
17
18
# File 'lib/googlemaps/services/geocoding.rb', line 16

def initialize(client)
  self.client = client
end

Instance Attribute Details

#clientSymbol

Returns The HTTP client.

Returns:

  • (Symbol)

    The HTTP client.

Since:

  • 1.0.0



14
15
16
# File 'lib/googlemaps/services/geocoding.rb', line 14

def client
  @client
end

Instance Method Details

#query(address: nil, components: nil, bounds: nil, region: nil, language: nil) ⇒ Array, Nokogiri::XML::NodeSet

Geocoding is the process of converting addresses (like “1600 Amphitheatre Parkway, Mountain View, CA”) into geographic coordinates (like latitude 37.423021 and longitude -122.083739), which you can use to place markers or position the map.

Parameters:

  • address (String) (defaults to: nil)

    The address to geocode.

  • components (Hash) (defaults to: nil)

    A component filter for which you wish to obtain a geocode. E.g. ‘TX’,‘country’: ‘US’

  • bounds (Hash) (defaults to: nil)

    The bounding box of the viewport within which to bias geocode results more prominently. The hash must have :northeast and :southwest keys.

  • region (String) (defaults to: nil)

    The region code, specified as a ccTLD (“top-level domain”) two-character value.

  • language (String) (defaults to: nil)

    The language in which to return results.

Returns:

  • (Array, Nokogiri::XML::NodeSet)

    Valid JSON or XML response.

Since:

  • 1.0.0



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/googlemaps/services/geocoding.rb', line 33

def query(address: nil, components: nil, bounds: nil, region: nil, language: nil)
  params = {}

  if address
    params['address'] = address
  end

  if components
    params['components'] = Convert.components(components)
  end

  if bounds
    params['bounds'] = Convert.bounds(bounds)
  end

  if region
    params['region'] = region
  end

  if language
    params['language'] = language
  end

  case self.client.response_format
  when :xml
    self.client.request(url: '/maps/api/geocode/xml', params: params).xpath('//result')
  when :json
    self.client.request(url: '/maps/api/geocode/json', params: params)['results']
  else
    raise StandardError, 'Unsupported response format. Should be either :json or :xml.'
  end
end