存储HTML5地理位置数据 [英] Storing HTML5 geolocation data

查看:108
本文介绍了存储HTML5地理位置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Rails 3中存储和处理网站用户的地理位置(long和lat),以便检查是否已经在每个页面请求的会话中为该用户保留了这些详细信息(if我们没有保留细节,那么我们应该从浏览器请求用户的位置,然后将这些细节存储在会话中)?

根据你的要求,我会说你实际上并不需要Ajax,因为大多数处理都是使用JS完成的(要求用户访问他们的位置,解析响应等),我会使用JS来设置一个cookie,然后Rails将会看到)。



在您的控制器中
$ b

  def动作
@lat_lng = cookies [:lat_lng] .split(|)
结尾

在您的视图中
$ b

 <% - 除非@lat_lng%> 
< script>
getGeoLocation();
< / script>
<% - end%>

在您的一个javascript文件中

 函数getGeoLocation(){
navigator.geolocation.getCurrentPosition(setGeoCookie);
}

函数setGeoCookie(position){
var cookie_val = position.coords.latitude +| + position.coords.longitude;
document.cookie =lat_lng =+ escape(cookie_val);
}

请注意,上述测试中没有一个用于查看用户是否拥有浏览器支持地理位置,或者如果用户已经授予(或拒绝)使用他们的位置的权限,并且cookie将是会话cookie,并且JS不测试以查看cookie是否已经设置。要在cookie上设置更复杂的信息,请查看 http://www.quirksmode.org/js /cookies.html 有关使用JavaScript的GeoLocation的详细信息,请参阅 http://diveintohtml5.info/geolocation.html


How can I store and process the geolocation (long and lat) of a website user in Rails 3, so that it checks to see if we're already holding those details in a session for that user on every page request (if we're not holding the details, then we should request the user's location from the browser and then store those details in the session)?

解决方案

Based on your requirements I'd say that you don't actually need ajax, since most of the processing will be done using JS (to ask the user for access to their location, parse the response etc), I'd use JS to set a cookie, which Rails will then see).

In your controller

def action
  @lat_lng = cookies[:lat_lng].split("|")
end

In your view

<%- unless @lat_lng %>
<script>
  getGeoLocation();
</script>
<%- end %>

In one of your javascript files

function getGeoLocation() {
  navigator.geolocation.getCurrentPosition(setGeoCookie);
}

function setGeoCookie(position) {
  var cookie_val = position.coords.latitude + "|" + position.coords.longitude;
  document.cookie = "lat_lng=" + escape(cookie_val);
}

Note that none of the above tests to see if the user has a browser that supports geolocation, or if the user has granted (or denied) permission to use their location, and that the cookie will be a session cookie, and that the JS doesn't test to see if the cookie is already set. To set more complicated information on the cookie take a look at http://www.quirksmode.org/js/cookies.html For more information on GeoLocation using javascript see http://diveintohtml5.info/geolocation.html

这篇关于存储HTML5地理位置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆