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

ε祈祈猫儿з 提交于 2019-12-02 19:51:41

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

jamesfzhang

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

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)
            });
        });
    }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!