HTML5 Geolocation In Rails

一笑奈何 提交于 2019-12-22 08:44:29

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/28202271/html5-geolocation-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!