use*_*971 3 ruby ajax html5 ruby-on-rails geolocation
看起来很简单,但我很挣扎.
这是我到目前为止的观点.我只显示位置坐标以测试其工作情况.但我也想坚持数据库,因此ajax调用.我是以正确的方式做到这一点还是有更简单或更好的方式?
<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>
Run Code Online (Sandbox Code Playgroud)
您可以尝试"更简单"的方式,使用geocoder gem,这提供了多种方法来获取用户位置,其中一种方法是按要求.
request.location.city => Medellin
request.location.country => Colombia
Run Code Online (Sandbox Code Playgroud)
您可以在以下链接中找到有用的信息