I am currently working on an application that customizes results based on the user's location, specifically the city they are browsing from. The location information will only be used for displaying relevant content and nothing else. I came across a helpful resource on this which I have integrated into my app.
In order to implement this functionality, I added the following code snippet to my _header partial:
<%- unless @lat_lng %>
<script>
getGeoLocation();
</script>
<%- end %>
This JavaScript code is included in my application.js file:
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);
}
In my controller's index action, I have added the following code:
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
Currently, the cookie is read every time a page loads. I would like to optimize this process by:
- Detecting the presence of the cookie on the initial page load,
- If the cookie exists, retrieve the location data,
- If the cookie does not exist, display the page content without location information,
- Once the user grants permission for location access, create the cookie, fetch the location data, and reload the page with this new information (potentially using ajax),
- Maintain the same location information until the user closes the browser tab, avoiding the need to read the cookie repeatedly on each page load.
Although I am not very familiar with JavaScript, I am exploring ways to achieve this functionality.