Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created May 10, 2016 23:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/731825befff43bb391f0c8bce48985fe to your computer and use it in GitHub Desktop.
Save JoshCheek/731825befff43bb391f0c8bce48985fe to your computer and use it in GitHub Desktop.
Set latitude and longitude into a cookie for a Rails server
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
<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