1

当我运行查询

Geocoder.search(@data.zip_code).inspect

输出如下哈希:

[#<Geocoder::Result::Google:0x007fc46360e8f0 @data={"address_components"=>[{"long_name"=>"92301",
"short_name"=>"92301", "types"=>["postal_code"]},
{"long_name"=>"Adelanto", "short_name"=>"Adelanto",
"types"=>["locality", "political"]}, {"long_name"=>"California",
"short_name"=>"CA", "types"=>["administrative_area_level_1",
"political"]}, {"long_name"=>"United States", "short_name"=>"US",
"types"=>["country", "political"]}], "formatted_address"=>"Adelanto,
CA 92301, USA",
"geometry"=>{"bounds"=>{"northeast"=>{"lat"=>34.82148189999999,
"lng"=>-117.35638}, "southwest"=>{"lat"=>34.506587,
"lng"=>-117.69486}}, "location"=>{"lat"=>34.6599838,
"lng"=>-117.5026174}, "location_type"=>"APPROXIMATE",
"viewport"=>{"northeast"=>{"lat"=>34.82148189999999,
"lng"=>-117.35638}, "southwest"=>{"lat"=>34.506587,
"lng"=>-117.69486}}}, "types"=>["postal_code"]}, @cache_hit=nil>]

我正在尝试访问这些信息(例如 field formatted_address),但我不知道如何获取这些数据。

在文档中写道:

Every Geocoder::Result object, result, provides the following data:
  result.latitude - float
  result.longitude - float
  result.coordinates - array of the above two
  ...

但是,这在这里不起作用(不确定我是否做错了什么或这些信息已过时)。

但是,如何从哈希中获取整个地址?

编辑: 解决方案:

puts Geocoder.search(@listing.zip_code)[0].data["formatted_address"]
# => Adelanto, CA 92301, USA

但是,当Geocoder调用将返回错误、未找到某些内容或连接超时时,我会收到错误消息。如何避免这种情况?我的目标是获取地址并将其发布到 Twitter,但是当我收到来自 Geocoder 的错误时,我不会将这些数据发布到 Twitter,而是会得到一个错误,这对用户不是很友好。

有什么方法可以检测此查询中的错误吗?

谢谢

4

0 回答 0