Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A rails app which gets users location using HTML5 geolocation and saves to data base

Seems pretty simple but I'm struggling.

Here's what I have so far in the view. I display the location coords just to test its working. But I also want to persist on Database, hence the ajax call. Am I doing this the right way or is there an easier or better way?

<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
    var x=document.getElementById("demo");
    var lat;
    var long;
    function getLocation()
    {
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(showPosition);

        }
        else{x.innerHTML="Geolocation is not supported by this browser.";}
    }
    function showPosition(position)
    {
        lat = position.coords.latitude;
        long = position.coords.longitude;
        x.innerHTML="Latitude: " + lat +
                "<br>Longitude: " + long;

        $.ajax({
            type: 'POST',
            url: 'http://localhost:3000/locations',
            data: { lat: lat, long: long },
            contentType: 'application/json',
            dataType: 'json'

        });
    }
</script>
like image 372
user2590971 Avatar asked Jan 19 '26 11:01

user2590971


1 Answers

You can try an "easier" way, use geocoder gem, this provides multiple methods in order to fetch the user location, one of them is by request.

request.location.city => Medellin
request.location.country => Colombia

You can find useful information in the following links

Railscast

Official WebPage

GitHub

like image 179
rderoldan1 Avatar answered Jan 22 '26 04:01

rderoldan1