Class: Google::Geocoder

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

Constant Summary collapse

URL_STRING =
"http://maps.googleapis.com/maps/api/geocode"
MAPS_URL_STRING =
"http://maps.google.com/maps?f=q&source=s_q&iwloc=A&hl=en"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.Exception(*names) ⇒ Object



32
33
34
35
# File 'lib/google_geocoder/google_geocoder.rb', line 32

def self.Exception(*names)
  cl = Module === self ? self : Object
  names.each {|n| cl.const_set(n, Class.new(Exception))}
end

Instance Method Details

#open_in_browser(q) ⇒ Object



84
85
86
87
88
89
# File 'lib/google_geocoder/google_geocoder.rb', line 84

def open_in_browser q
  location = q.gsub(/\s/, '+')
  lng, lat = query(q)

  Launchy::Browser.run("#{MAPS_URL_STRING}&geocode=&q=#{location}&sll=#{lng},#{lat}&hnear=#{location}")
end

#query(location) ⇒ Object

Raises:

  • (MissingLocation)


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/google_geocoder/google_geocoder.rb', line 42

def query(location)
  raise(MissingLocation) if location.nil?

  request = "#{URL_STRING}/json?address=#{CGI.escape(location)}&sensor=false"

  begin
    response = call_service(request)

    raise(GeocoderServerIsDown) if response.empty?

    if response['status'] == "ZERO_RESULTS"
      []
    else
      raise(InvalidResponse, response['results']) if response['status'] != "OK" # success

      root = response["results"][0]
      address_components = root["address_components"]
      geometry = root["geometry"]

      country = address_component(address_components, "country")
      locality = address_component(address_components, "locality")
      administrative_area_l1 = address_component(address_components, "administrative_area_level_1")
      administrative_area_l2 = address_component(address_components, "administrative_area_level_2")

      latitude = geometry["location"]["lat"]
      longitude = geometry["location"]["lng"]

      puts "Country: #{country['long_name']} (#{country['short_name']})"
      puts "Locality: #{locality['long_name']} (#{locality['short_name']})"
      puts "Administrative Area (level 1): #{administrative_area_l1['long_name']} (#{administrative_area_l1['short_name']})"
      puts "Administrative Area (level 2): #{administrative_area_l2['long_name']} (#{administrative_area_l2['short_name']})" unless administrative_area_l2.nil?

      puts "Latitude: #{latitude}"
      puts "Longitude: #{longitude}"

      [latitude, longitude]
    end
  rescue OpenURI::HTTPError
    raise(GeocoderServerIsDown)
  end
end