問題描述
如何在 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 地理位置數據的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!