Class: GoogleMaps::Services::ReverseGeocode

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

Overview

Performs requests to the Google Maps Geocoding API.

Examples:

reverse_geocode = GoogleMaps::Services::ReverseGeocode.new(client)
result = reverse_geocode.query(latlng: {:lat => 52.520645, :lng => 13.409779}, language: "fr")

Since:

  • 1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ ReverseGeocode

Returns a new instance of ReverseGeocode.

Since:

  • 1.0.0



79
80
81
# File 'lib/googlemaps/services/geocoding.rb', line 79

def initialize(client)
  self.client = client
end

Instance Attribute Details

#clientObject

Since:

  • 1.0.0



77
78
79
# File 'lib/googlemaps/services/geocoding.rb', line 77

def client
  @client
end

Instance Method Details

#query(latlng:, result_type: nil, location_type: nil, language: nil) ⇒ String

Reverse geocoding is the process of converting geographic coordinates into a human-readable address.

Parameters:

  • latlng (String, Hash)

    The lat/lng value or place_id for which you wish to obtain the closest, human-readable address.

  • result_type (Array) (defaults to: nil)

    One or more address types to restrict results to.

  • location_type (Array) (defaults to: nil)

    One or more location types to restrict results to.

  • language (String) (defaults to: nil)

    The language in which to return results.

Returns:

  • (String)

    Valid JSON or XML response.

Since:

  • 1.0.0



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/googlemaps/services/geocoding.rb', line 91

def query(latlng:, result_type: nil, location_type: nil, language: nil)
  # Check if latlng param is a place_id string.
  # 'place_id' strings do not contain commas; latlng strings do.
  if latlng.is_a?(String) && !latlng.include?(",")
    params = {'place_id' => latlng}
  else
    params = {'latlng' => Convert.to_latlng(latlng)}
  end

  if result_type
    params['result_type'] = Convert.join_array('|', result_type)
  end

  if location_type
    params['location_type'] = Convert.join_array('|', location_type)
  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)
        .fetch('results', [])
  else
    raise StandardError, 'Unsupported response format. Should be either :json or :xml.'
  end
end