Rails中的HTML5地理定位 [英] HTML5 Geolocation In Rails

查看:94
本文介绍了Rails中的HTML5地理定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过HTML5获取用户位置并将其传递给我的rails控制器。



我在下面的JavaScript中调用元素的.value,并将它设置为相应的位置。然后,我想通过隐藏的表单字段提交这些值,并将其传递到我的位置控制器,以便我可以根据用户的位置来填充位置。我知道这已经完成,我已经看到了一些帖子,但我没有成功。

  navigator。 geolocation.getCurrentPosition(GEOL); 
函数GeoL(position){
document.getElementById('lat')。value = position.coords.latitude;
document.getElementById('lon')。value = position.coords.longitude;
}

<%= form_tag locations_path,:method =>'post'do%>
<%= hidden_​​field_tag'lat',value =''%>
<%= hidden_​​field_tag'lon',value =''%>
<%= image_submit_tag'loc.png'%>
<%end%>

def创建
这里有什么?抓取参数?这是正确的操作吗?
end

我目前收到您在下面的屏幕截图中看到的错误。我认为我的表单可能需要一些工作,另外我需要在我的控制器中添加代码来获取值。正如你可以看到有点失落,任何建议都会很棒。



解决方案

据我所知,你想根据用户的位置显示位置。这意味着你可以像你已经做过的那样找到用户,把经纬度写入 hidden_​​form_field s并通过ajax发送到索引 locations_controller (不是创建操作)的c $ c>(!)动作。 使用地理编码器控制器看起来像这样:

  @locations = Location.near([params [:lat],params [:lon]]) 



respond_to do | format |
format.html {}
format.js {}
结束

然后,您只需将新的 @locations 插入到您的索引视图中


I am trying to grab a users location via HTML5 and pass it to my rails controller.

I have the JavaScript below which calls .value on the element and sets it equal to the respective position. I would then like to submit these values through a hidden form field and pass it to my location controller so I can populate locations based on the users position. I know this has been done before and I have seen a few posts on it, but I have not had success.

navigator.geolocation.getCurrentPosition(GeoL);
function GeoL(position) {
  document.getElementById('lat').value = position.coords.latitude;
  document.getElementById('lon').value = position.coords.longitude;
}

<%= form_tag locations_path, :method=>'post' do %>
  <%= hidden_field_tag 'lat', value = ''%>
  <%= hidden_field_tag 'lon', value = ''%>
  <%= image_submit_tag 'loc.png'  %>
<% end %>

def create
 "What goes here? Grab params? Is this the right action to send it to?"
end

I am currently getting the error you see in this screen shot below. I think my form may need some work, plus I need to add code in my controller to grab the values. As you can see a little lost, any advice would be great.

解决方案

As i understand you, you would like to show locations based on the users position. That means you locate the user like you already did, write lat and lon into the hidden_form_fields and send this form via ajax to the index (!) action of your locations_controller (not the create action).

With geocoder the controller looks something like that:

@locations = Location.near([params[:lat], params[:lon]])
.
.
.
respond_to do |format|
 format.html {}
 format.js {}
end

Then you only have to insert your new @locations into your index view

这篇关于Rails中的HTML5地理定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆