3

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>
user2590971
  • 35
  • 1
  • 5

3 Answers3

7

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

rderoldan1
  • 3,517
  • 26
  • 33
  • It is a great gem and very useful - However it is no where near as accurate as HTML5 geolocation. Its a good fallback though. – John Kloian Dec 23 '14 at 21:50
2

Check out this answer. Basically, just set the geolocation via a cookie and read the lat and long from the cookie in your controller.

Community
  • 1
  • 1
jamesfzhang
  • 4,403
  • 8
  • 32
  • 43
0

Here's how I did it:

controller:

def location
    respond_to do |format|
      format.json {
        lat = params["lat"]
        lng = params["lng"]
        radius = 5000
        type = "restraunt"
        key = "-"
        url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=#{lat},#{lng}&radius=#{radius}&types=#{type}&key=#{key}"
        data = JSON.load(open(url))
        render json: { :data => data }
      }
    end
  end

routes.rb:

get "/location" => "application#location"

view:

function getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position){
          $.ajax({
            type: 'GET',
            url: '/location',
            data: { lat: position.coords.latitude, lng: position.coords.longitude },
            contentType: 'application/json',
            dataType: 'json'
            }).done(function(data){
               console.log(data)
            });
        });
    }
  }
Max Dubinin
  • 214
  • 3
  • 20