一个rails应用程序,使用HTML5地理定位获取用户位置并保存到数据库

看起来很简单,但我很挣扎。

这是我到目前为止的观点。 我只显示位置坐标以测试其工作情况。 但我也想坚持数据库,因此ajax调用。 我是以正确的方式做到这一点还是有更简单或更好的方式?

Click the button to get your coordinates:

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 + "
Longitude: " + long; $.ajax({ type: 'POST', url: 'http://localhost:3000/locations', data: { lat: lat, long: long }, contentType: 'application/json', dataType: 'json' }); }

你可以尝试一种“更简单”的方式,使用geocoder gem,这提供了多种方法来获取用户位置,其中一种是按要求。

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

您可以在以下链接中找到有用的信息

Railscast

官方网页

GitHub上

看看这个答案 。 基本上,只需通过cookie设置地理位置,然后从控制器中的cookie读取lat和long。

我是这样做的:

控制器:

 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" 

视图:

 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) }); }); } }