简体   繁体   中英

Ruby on Rails - How to Use HTML Coordinates in a Rails Method?

Thanks to whoever will answer me.

I have a method that currently works like this post.distance_to([current_user.latitude, current_user.longitude]) . It returns the distance between a post (with an address) and the current_user.

I created the attributes latitude and longitude in the user model because I don't know how to use directly these coordinates that I retrieve with the following script:

<p id="geoloc"></p>
<script>
  var x = document.getElementById("geoloc");

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(getCoordinates);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function getCoordinates(position) {
    var new_latitude = position.coords.latitude;
    var new_longitude = position.coords.longitude;

    $(document).ready(function () {
      $("#latitude_field").val(new_latitude);
      $("#longitude_field").val(new_longitude);
    }
  }

  getLocation()
</script>

Currently I'm updating the user model with the new coordinates by pressing a button using this form:

<%= form_for(current_user) do |f|  %>
  <%=f.hidden_field :latitude ,:id=> "latitude_field" %>
  <%=f.hidden_field :longitude ,:id=> "longitude_field" %>
  <%=f.submit "I'm here", class: "btn btn-small btn-primary jsbuttons"%>
<%end%>

What I would like to do is calling the method directly like this post.distance_to(["latitude obtained with the script", "longitude obtained with the script"]) . How can I make rails know what those coordinates are? Can I use those javascript id I use in the form to just get the values and place them in the method somehow? Thanks!

If that's too complicated can I update the user model with the new coordinates every time I refresh the page without having to press a button? (I tried to make an id for the form and place a submit in the $(document).ready(function) for that id but it didn't work)

Use the following code for your form:

<%= form_tag '/your_url' do |f|  %>
  <%=f.text_field_tag :latitude, params[:latitude], :id=> "latitude_field" %>
  <%=f.text_field :longitude, params[:longitude], :id=> "longitude_field" %>
  <%=f.submit "I'm here", class: "btn btn-small btn-primary jsbuttons"%>
<% end %>

Now in your controller action you access lat/long using:

lat = params[:latitude]
lng = params[:longitude]
distance = post.distance_to([lat,lng])

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