简体   繁体   中英

HTML5 Geolocation In Rails

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_field s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM