class OpenCage::Geocoder

Constants

GeocodingError

Public Class Methods

new(default_options = {}) click to toggle source
# File lib/opencage/geocoder.rb, line 10
def initialize(default_options = {})
  @api_key = default_options.fetch(:api_key) { raise GeocodingError, 'missing API key' }
end

Public Instance Methods

geocode(location, options = {}) click to toggle source
# File lib/opencage/geocoder.rb, line 14
def geocode(location, options = {})
  request = Request.new(@api_key, location, options)

  results = fetch(request.to_s)
  return [] unless results

  results.map { |r| Location.new(r) }
end
reverse_geocode(lat, lng, options = {}) click to toggle source
# File lib/opencage/geocoder.rb, line 23
def reverse_geocode(lat, lng, options = {})
  if [lat, lng].any? { |coord| !coord.is_a?(Numeric) }
    raise GeocodingError, "not valid numeric coordinates: #{lat.inspect}, #{lng.inspect}"
  end

  geocode("#{lat},#{lng}", options).first
end

Private Instance Methods

error_message(error) click to toggle source
# File lib/opencage/geocoder.rb, line 39
def error_message(error)
  case String(error)
  when /^403/
    'invalid API key'
  when /^402/
    'out of quota'
  else
    error
  end
end
fetch(url) click to toggle source
# File lib/opencage/geocoder.rb, line 33
def fetch(url)
  JSON.parse(URI(url).open.read)['results']
rescue OpenURI::HTTPError => e
  raise GeocodingError, error_message(e)
end