Reputation: 711
I am using the HTML 5 Geolocation code (http://www.w3schools.com/html/html5_geolocation.asp) to get the users location.
...
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
I want to create a variable in ruby that holds the value of position.coords.latitude and position.coords.longitude, does anyone know the most effective way to capture this information and save it as a ruby variable?
Upvotes: 0
Views: 859
Reputation: 5774
Well there are 2 ways you can do this -
Make ajax call
var latitude = position.coords.latitude;
var longitude = position.coords.latitude;
$.ajax({
url: "/<some_route>?latitude="+latitude+"&longitude="+longitude,
success: function(data) {
// do something here like for example replace some arbitrary container's html with the stuff returned by server.
$("#container").html(data);
}
});
Access it on the server side using params hash
latitude = params[:latitude]
longitude = params[:longitude]
Set a location cookie on the client side and access it on the server side.
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
document.cookie = "cl=" + latitude + "&" + longitude + ";";
And in your controller you can access this -
current_location = cookies[:cl]
unless current_location.nil?
latitude = current_location.split('&')[0]
longitude = current_location.split('&')[1]
end
Having said that you should prefer option 1 because cookies are sent to the server with each HTTP request and additionally you might need to inform users that tracking technologies are used.
Upvotes: 2
Reputation: 48589
does anyone know the most effective way to capture this information and save it as a ruby variable?
What is your measurement of effective? The data won't be missing a random digit when it gets to the server?
Making a jQuery ajax request is easiest:
var lat = 10;
var lon = 20;
function onsuccess(data, textStatus, jqXHR) {
alert(textStatus);
}
$.post(
"http://localhost:3000/some/route",
{'lat': lat, 'lon': lon},
onsuccess //optional
);
The latitude and longitude can be retrieved inside your action from the params hash:
lat = params[:lat]
lon = params[:lon]
Upvotes: 0
Reputation: 20096
A request have, on high, the following steps:
The question of how to have a variable that is only present in 3
on step 2
, this is impossible.
An alternative is simply add an ajax call (that is, repeat steps 1 to 3, but instead of "Browser" read "Javascript code") that sends this information to the server to save in the database or something, but you will still have to program your logic in javascript.
Upvotes: 1