从谷歌获取Lat Long

时间:2013-07-17 16:01:20

标签: ruby json geocoding

我想要搜索位置的代码,它将返回lat和long。我正在使用Google的Geocode API。我有发送请求等的代码,它返回以下内容:

{"results"=>[{"address_components"=>[{"long_name"=>"London", "short_name"=>"London", "types"=>["locality", "political"]}, {"long_name"=>"United Kingdom", "short_name"=>"GB", "types"=>["country", "political"]}], "formatted_address"=>"London, UK", "geometry"=>{"bounds"=>{"northeast"=>{"lat"=>51.6723432, "lng"=>0.1478797}, "southwest"=>{"lat"=>51.38494009999999, "lng"=>-0.3514683}}, "location"=>{"lat"=>51.51121389999999, "lng"=>-0.1198244}, "location_type"=>"APPROXIMATE", "viewport"=>{"northeast"=>{"lat"=>51.6723432, "lng"=>0.1478797}, "southwest"=>{"lat"=>51.38494009999999, "lng"=>-0.3514683}}}, "types"=>["locality", "political"]}], "status"=>"OK"}

我希望从上面的回复中获取Lat和Lng,并将它们分配给两个变量。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

h = {"results"=>[{"address_components"=>[{"long_name"=>"London", "short_name"=>"London", "types"=>["locality", "political"]}, {"long_name"=>"United Kingdom", "short_name"=>"GB", "types"=>["country", "political"]}], "formatted_address"=>"London, UK", "geometry"=>{"bounds"=>{"northeast"=>{"lat"=>51.6723432, "lng"=>0.1478797}, "southwest"=>{"lat"=>51.38494009999999, "lng"=>-0.3514683}}, "location"=>{"lat"=>51.51121389999999, "lng"=>-0.1198244}, "location_type"=>"APPROXIMATE", "viewport"=>{"northeast"=>{"lat"=>51.6723432, "lng"=>0.1478797}, "southwest"=>{"lat"=>51.38494009999999, "lng"=>-0.3514683}}}, "types"=>["locality", "political"]}], "status"=>"OK"}

lat, lng = h["results"].first["geometry"]["location"].values_at("lat", "lng")
lat # => 51.51121389999999
lng # => -0.1198244

答案 1 :(得分:1)

lat, lng = *result['results'][0]['geometry']['location'].values