Class: SimpleGeocoder::Geocoder

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_geocoder/geocoder.rb

Constant Summary collapse

@@api_config =
YAML.load_file(File.join(File.dirname(__FILE__), '../../config/api.yml'))

Instance Method Summary collapse

Constructor Details

#initializeGeocoder

Returns a new instance of Geocoder.



14
15
16
# File 'lib/simple_geocoder/geocoder.rb', line 14

def initialize
  
end

Instance Method Details

#find_location(address) ⇒ Object

if geocoding fails, then look for lat,lng string in address



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/simple_geocoder/geocoder.rb', line 36

def find_location(address)
  result = geocode(address)
  if result['status'] == 'OK'
    return result['results'][0]['geometry']['location']
  else
    latlon_regexp = /(-?([1-8]?[0-9]\.{1}\d{1,6}|90\.{1}0{1,6})),(-?((([1]?[0-7][0-9]|[1-9]?[0-9])\.{1}\d{1,6})|[1]?[1-8][0]\.{1}0{1,6}))/
    if address =~ latlon_regexp
      location = $&.split(',').map {|e| e.to_f}
      return { "lat" => location[0], "lng" => location[1] }
    else
      return nil
    end
  end
end

#geocode(address, options = {}) ⇒ Object

swallow exceptions and return nil on error



19
20
21
22
23
# File 'lib/simple_geocoder/geocoder.rb', line 19

def geocode(address, options = {})
  geocode!(address, options)
rescue ResponseError
  nil
end

#geocode!(address, options = {}) ⇒ Object

raise ResponseError exception on error



26
27
28
29
30
31
32
33
# File 'lib/simple_geocoder/geocoder.rb', line 26

def geocode!(address, options = {})
  response = call_geocoder_service(address, options)
  if response.is_a?(Net::HTTPOK)
    return JSON.parse response.body
  else
    raise ResponseError.new response
  end
end