我的目标是让用户在表格中输入坐标(经度和纬度)。表单采用params哈希响应,并使用谷歌地理编码器API指定位置。然后,我希望使用距离矩阵API将该位置与另一个用户位置进行比较,该距离矩阵API将找到用户之间的距离。
以下是我的路线:
get "/users/:id/runwith" => 'application#runwith'
get "/reversegeocode" => 'application#reversegeocode'
这是控制器:
def runwith
end
def reversegeocode
@users = User.all
lat = params['longitude']
long = params['latitude']
url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=#{lat},#{long}"
result = open(url).read
parsed_result = JSON.parse(result)
@location = parsed_result['results'][0]['formatted_address'].gsub(" ", "%20")
end
我的自定义方法:
private
def location some_runner
@users = User.all
distance_url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#{@location}&destinations=#{some_runner.location}"
distance_parsed_result = JSON.parse(open(distance_url).read)
{distance: distance_parsed_result['rows'][0]["elements"][0]["distance"]["text"], duration: distance_parsed_result['rows'][0]["elements"][0]["duration"]["text"]}
end
helper_method :location
end
我的表单html:
<% if session[:user_id] %>
<h1> You are already logged in there is no need to specify your location </h1>
<%else%>
<h1> Since you aren't logged in, where are you currently? </h1>
<form action ="/reversegeocode">
Longitude:<input name ="longitude" type ="text" placeholder="coordinates">
Latitude:<input name ="latitude" type ="text" placeholder="coordinates">
<input type="submit">
</form>
<%end%>
我的最终结果是reversegeocode.html.erb:
<% @users.each do |user| %>
<h1> <%=@location.gsub("%20"," ")%> </h1>
<% data = location.location(user) %>
<!-- <h1>You are <%#=data[:distance]%> far from <%#=data[:duration]%> </h1> -->
<%end%>
然而,我不断得到错误的参数数量(0表示1),def位置some_runner。为什么?