我要在此处进行的操作是获取用户(浏览器)的地理位置,使用隐藏字段来保存经度和纬度,一旦表单发布(上传了图片),纬度和经度将显示在通知中(将稍后在模型中使用它们来存储它们)。我在这里遇到的问题是,在发布之前,我必须刷新几次才能得到Lat,Long。否则,表单将同时提交两个值。这是我正在使用的相关代码:
app / assets / javascript / html5geolocatio.js
$(document).ready(function() {
navigator.geolocation.getCurrentPosition(
onSuccess,
onError, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 120000
}
);
function onSuccess(position) {
myPosition[0] = position.coords.latitude;
myPosition[1] = position.coords.longitude;
document.getElementById("image_lon").value = position.coords.longitude;
document.getElementById("image_lat").value = position.coords.latitude;
}
function onError(err) {
var message;
switch (err.code) {
case 0:
message = 'Unknown error: ' + err.message;
break;
case 1:
message = 'You denied permission to retrieve a position.';
break;
case 2:
message = 'The browser was unable to determine a position: ' + error.message;
break;
case 3:
message = 'The browser timed out before retrieving the position.';
break;
}
}
});
图像控制器:
def create
@photo = current_user.images.build(image_params)
if @photo.save
flash[:notice] = "Photo has been uploaded" + params[:image][:lat]+ ',' + params[:image][:lon]
redirect_to root_url
else
render 'static_pages/home'
end
end
上载表格:
<%= form_for @photo do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.file_field :image %>
<%= f.hidden_field :lon %>
<%= f.hidden_field :lat %>
<%= f.submit "Upload Photo" %>
<% end %>
另外,如果有更好的方法可以解决此问题,请告诉我。提前致谢。
这是有关如何将JavaScript变量传递到Rails应用程序的示例:https : //github.com/lorenzosinisi/javascript-variable-to-rails-controller
您可以将变量写入Cookie,然后从控制器进行访问,如下所示:
在视图中(使用javascript):
document.cookie = "latitudine="+latitude;
document.cookie = "longitudine="+longitude;
并在控制器中:
@latitudine_full = cookies[:latitudine].nil? ? '0.00' : cookies[:latitudine]
@longitudine_full = cookies[:longitudine].nil? ? '0.00' : cookies[:longitudine]
重新加载页面后,这将起作用。
如果您要在发布后清除/删除Cookie,可以使用javascript
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句