【发布时间】:2015-09-08 08:08:14
【问题描述】:
感谢愿意回答我的人。
我有一个方法,目前像 post.distance_to([current_user.latitude, current_user.longitude]) 这样工作。它返回帖子(带有地址)和 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 提交,但没有成功)
【问题讨论】:
标签: javascript html ruby-on-rails geolocation coordinates