2012-06-09 24 views
0

我試圖獲取特定位置的經度和緯度以下http://ruby.bastardsbook.com/chapters/methods-and-gems/不能把字符串轉換成整數,而解析谷歌地圖API

Here is the snippet: 
require 'rubygems' 
require 'rest-client' 
require 'crack' 

def get_coordinates_from_address(addr) 
    base_google_url = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=" 
    res = RestClient.get(URI.encode("#{base_google_url}#{addr}")) 
    parsed_res = Crack::XML.parse(res) 
    lat = parsed_res["GeocodeResponse"]["result"]["geometry"]["location"]["lat"] 
    lng = parsed_res["GeocodeResponse"]["result"]["geometry"]["location"]["lng"] 

    return "#{lat}, #{lng}" 
end  

latlng = get_coordinates_from_address("1 Times Square, NYC") 
puts latlng 

我收到以下堆棧跟蹤:

/Users/archie/agile/latlang.rb:9:in `[]': can't convert String into Integer (TypeError) 
    from /Users/archie/agile/latlang.rb:9:in `get_coordinates_from_address' 
    from /Users/archie/agile/latlang.rb:15:in `<main>' 
[Finished] 

可能的問題是什麼?

回答

1

我想我知道。 The XML有幾個result s,所以parsed_res["GeocodeResponse"]["result"]確實是一個數組。我真的不知道紅寶石或裂紋,但我的預感是,你需要解決的指數導致(通常是第一個結果是最好的,所以用0),喜歡寫東西

parsed_res["GeocodeResponse"]["result"][0]["geometry"]["location"]["lat"] 

也許

firstResult = parsed_res["GeocodeResponse"]["result"][0] 
lat = firstResult["geometry"]["location"]["lat"] 

我的符號可能是錯的,對不起!

+1

也可能值得注意的是,這些值不是整數,並且將字符串轉換爲整數可能不會給出預期的結果。 –

相關問題