I am developing an app that shows some results depending on the "city" that the user is browsing my app. I'll only use this location info for displaying some results, nothing more. I read this and implemented to my app.
I put this code to my _header partial:
<%- unless @lat_lng %>
<script>
getGeoLocation();
</script>
<%- end %>
this code to application.js:
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);
}
and this code to my controller index action:
if cookies().key?("lat_lng")
lat_lng = cookies[:lat_lng].split("|")
geo_localization = "#{lat_lng[0]},#{lat_lng[1]}"
query = Geocoder.search(geo_localization).first
@city = query.state
else
@city = "nocity"
end
But now every time any page loads, I read the cookie again. How can I:
- Look if the cookie exists at the first page loads,
- If exists, read the location
- If it does not, load the page content without location info.
- After the user allowed the location request, create the cookie and find the location, reload the page content with the location data (using ajax or somethng)
- Use the same location until the user closes my app page on the browser, not read the cookie every time a page loads.
By the way I'm not familiar with javascript but trying to handle.