Class: GoogleGeocoding::Response

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

Instance Method Summary collapse

Constructor Details

#initialize(resp_body) ⇒ Response

Creates a new response object from the given response body, expects to be a JSON string.

Parameters:

  • (String)


6
7
8
# File 'lib/google_geocoding/response.rb', line 6

def initialize(resp_body)
  @data = JSON.parse(resp_body)
end

Instance Method Details

#failure?Boolean

Return whether response failed to resolved the geolocation

Returns:

  • (Boolean)


24
25
26
# File 'lib/google_geocoding/response.rb', line 24

def failure?
  !success?
end

#placemarksArray<Placemark>

Return the placemarks included in the response.

Returns:



31
32
33
34
35
36
37
38
39
40
41
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
# File 'lib/google_geocoding/response.rb', line 31

def placemarks
  if failure?
    raise Errors::ServiceError.build(status_code)
  else
    placemarks = []
    
    @data["Placemark"].each do |placemark_data|
      details               = placemark_data["AddressDetails"]
      coordinates           = placemark_data["Point"]["coordinates"][2..1]
      accurracy             = Integer(details["Accuracy"])
      placemark             = Placemark.new
      placemark.accurracy   = accurracy
      placemark.coordinates = coordinates
      
      next if accurracy >= 9

      if accurracy >= 1
        country = details["Country"]
        placemark.country_name = country["CountryName"],
        placemark.country_code = country["CountryNameCode"]
        
        if accurracy >= 2
          admarea = country["AdministrativeArea"]
          placemark.region = admarea["AdministrativeAreaName"]
          
          if accurracy >= 3
            subadmarea = admarea["SubAdministrativeArea"]
            
            if accurracy >= 4
              locality = subadmarea ? subadmarea["Locality"] : admarea["Locality"]
              placemark.city = locality["LocalityName"]
              
              if accurracy >= 5
                placemark.postal_code = locality["PostalCode"]["PostalCodeNumber"]
              end
              
              if accurracy >= 6
                placemark.street = locality["Thoroughfare"]["ThoroughfareName"]
              end
            end
          end
        end
      end
      
      placemarks << placemark
    end
    placemarks
  end
end

#status_codeInteger

Return the status code included in the server response.



14
15
16
# File 'lib/google_geocoding/response.rb', line 14

def status_code
  Integer(@data["Status"]["code"])
end

#success?Boolean

Return whether response successfully resolved the geolocation

Returns:

  • (Boolean)


19
20
21
# File 'lib/google_geocoding/response.rb', line 19

def success?
  status_code == 200
end