Created
May 10, 2016 23:05
-
-
Save JoshCheek/731825befff43bb391f0c8bce48985fe to your computer and use it in GitHub Desktop.
Set latitude and longitude into a cookie for a Rails server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pp' | |
class SomeController < ApplicationController | |
def omg | |
# cookies.delete 'latlon' | |
@cookies = cookies.to_h | |
# now probably move these to helper methods in application controller | |
@latitude, @longitude = | |
cookies['latlon'].to_s.split('|') | |
.map(&:to_f) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h2>Was JS run?</h2> | |
<div id="was-js-run">No</div> | |
<h2>Latitude / Longitude</h2> | |
<p>(<%= @latitude %>, <%= @longitude %>)</p> | |
<h2>Cookies (from server):</h2> | |
<pre><%= @cookies.pretty_inspect %></pre> | |
<script> | |
// found the regex here: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie | |
var match = document.cookie.match(/(?:(?:^|.*;\s*)latlon\s*\=\s*([^;]*).*$)|^.*$/); | |
var cookieValue = (match && match[1]); | |
if(cookieValue) | |
console.log("Looks like: " + cookieValue); | |
if(!cookieValue && navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(function(geoPosition) { | |
var coords = geoPosition.coords | |
document.cookie = ("latlon=" + coords.latitude + "|" + coords.longitude); | |
$('#was-js-run').text('YES!').css('background-color', 'green') | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment