如何在Rails方法中使用HTML坐标

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

本文关键字:HTML 坐标 方法 Rails      更新时间:2023-09-26

感谢回答我问题的人。

我有一个方法,目前工作像这样的post.distance_to([current_user.latitude, current_user.longitude])。它返回post(带有地址)和current_user之间的距离。

我在用户模型中创建了属性纬度和经度,因为我不知道如何直接使用我用以下脚本检索的这些坐标:

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

目前我正在更新用户模型与新的坐标通过按下一个按钮使用这个表单:

<%= 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%>

我想做的是像这样直接调用方法post.distance_to(["latitude obtained with the script", "longitude obtained with the script"])。如何让rails知道这些坐标呢?能否使用表单中使用的javascript id获取值并将其放入方法中?谢谢!

如果这太复杂,我是否可以在每次刷新页面时使用新的坐标来更新用户模型,而无需按下按钮?(我试图为表单创建一个id,并在$(document).ready(function)中提交该id,但它没有工作)

为您的表单使用以下代码:

<%= 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 %>

现在在你的控制器操作中,你使用:

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