我正在开发一个Rails应用程序,我想使用Javascript的导航API来获取用户的地理位置。我在"app/javascript/location_controller"下的控制器中有代码,它可以工作。
import { Controller } from "stimulus"
export default class extends Controller {
connect(){
this.getUserLocation()
}
getUserLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => console.log(position.coords), (error)=> console.log(error));
} else {
alert("Could not get your current location! Please allow location services for RiseUp.")
}
}
}
如何从Rails Helper调用"getUserLocation"?
刺激控制器,以及通常任何javascript,都不是由您的ruby服务器运行的,而是由用户的浏览器运行的。
如果你想从中获取一个值,你需要进行一些ajax调用,并从一个普通的rails控制器中获取它。
类似于:
async getUserLocation() {
let data = new FormData();
let position = await navigator.geolocation.getCurrentPosition();
data.set('position', position);
await fetch('/api/notify_location', {method: 'POST', body: data, credentials: true});
}
你必须在后端路由它:
scope 'api' do
post 'notify_location' => 'location#notify'
end
并将其放入控制器
class LocationController < ApplicationController
def notify
# do as needed, you will be able to get the session here
# because the fetch function was passed credentials: true
# but beware, this request won't match `request.xhr?` because
# fetch is not XMLHTTPRequest.