Class: SpreeCmCommissioner::GoogleMapsGeocoder

Inherits:
Object
  • Object
show all
Defined in:
app/services/spree_cm_commissioner/google_maps_geocoder.rb

Defined Under Namespace

Classes: ConfigurationError, GeocodingError

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil) ⇒ GoogleMapsGeocoder

Returns a new instance of GoogleMapsGeocoder.



6
7
8
# File 'app/services/spree_cm_commissioner/google_maps_geocoder.rb', line 6

def initialize(api_key: nil)
  @api_key = api_key || ENV.fetch('GOOGLE_MAP_KEY', nil)
end

Instance Method Details

#fetch_location_data(location_name, country_name) ⇒ Object

Raises:



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'app/services/spree_cm_commissioner/google_maps_geocoder.rb', line 10

def fetch_location_data(location_name, country_name)
  raise ConfigurationError, 'Google Maps API key not configured' if @api_key.blank?

  query = "#{location_name}, #{country_name}"
  url = "#{GOOGLE_MAP_API_URL}/place/textsearch/json"
  params = { query: query, key: @api_key }

  response = Faraday.get(url, params)

  begin
    data = JSON.parse(response.body)
  rescue JSON::ParserError => e
    raise GeocodingError, "Failed to parse Google Maps API response: #{e.message}"
  end

  unless data['status'] == 'OK' && data['results'].present?
    error_msg = "Geocoding failed for '#{query}': #{data['status']}"
    error_msg += " - #{data['error_message']}" if data['error_message'].present?
    raise GeocodingError, error_msg
  end

  result = data['results'].first
  location = result['geometry']['location']

  {
    lat: location['lat'],
    lon: location['lng'],
    reference: result['reference']
  }
end