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

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

问题描述

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

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

推荐答案

根据您的要求,我想说您实际上并不需要 ajax,因为大部分处理将使用 JS 完成(询问用户访问他们的位置,解析响应等),我会使用 JS 设置一个 cookie,Rails 会看到).

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

在您的控制器中

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

在你看来

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

在您的一个 javascript 文件中

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);
}

请注意,上述测试都不是为了查看用户是否拥有支持地理定位的浏览器,或者用户是否已授予(或拒绝)使用其位置的权限,并且该 cookie 将是一个会话 cookie,并且JS 不会测试是否已经设置了 cookie.要在 cookie 上设置更复杂的信息,请查看 http://www.quirksmode.org/js/cookies.html 有关使用 javascript 的 GeoLocation 的更多信息,请参阅 http://diveintohtml5.info/geolocation.html

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天全站免登陆