2011-12-19 45 views
0

我試圖在Sinatra應用程序中使用Google Maps API。每當我查找地址時,都會收到TypeError(無法將字符串轉換爲整數)。摘要Google Maps API時出現TypeError

看看我的代碼,讓我知道你認爲問題是什麼。

require 'sinatra' 
require 'json' 
require 'open-uri' 


get '/' do 
    haml :index 
end 

post '/' do 
    find_location(params[:location]) 
end 

def find_location(address) 
    url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + CGI.escape(address) + "&sensor=false" 
    resp = open(url).read 
    parsed_resp = JSON.parse(resp) 
    lat = parsed_resp['results']['geometry']['location']['lat'] 
    lng = parsed_resp['results']['geometry']['location']['lng'] 
    lat + " " + lng 
end 

回答

1

parsed_resp['results']是一個數組,所以你的代碼應該是這樣的:

def find_location(address) 
    url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + CGI.escape(address) + "&sensor=false" 
    resp = open(url).read 
    parsed_resp = JSON.parse(resp) 
    unless parsed_resp['results'].empty? 
    lat = parsed_resp['results'].first['geometry']['location']['lat'].to_s 
    lng = parsed_resp['results'].first['geometry']['location']['lng'].to_s 
    lat + " " + lng 
    end 
end