当我运行查询时
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>]
我正在尝试访问这些信息(例如字段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上,而是会收到错误,这对用户不太友好。
有没有办法检测此查询中的错误?
谢谢