htmlのstartボタンを押したら今の現在地の緯度と経度をデータベースに保存するようにしたいです。
保存後にそのページと別のページにリダイレクトしたいと考えています。
しかし、うまくいかないので教えてください。
routes.rb
"hoge/:id" => "hoge#start"
html.slim
input type="button" value="start" onclick="hogehoge(#{@hoge.id})"
hoge.js
function hogehoge(x) { if (navigator.geolocation) { //現在地取得可能 navigator.geolocation.getCurrentPosition( function(position) {//success var data = position.coords; var lat = data.latitude; var lng = data.longitude; $.post({ url: "/hoge/"+x, data: {latitude: lat, longitude: lng}, dataType: 'json', success: function(){ alert("success") }, error: function(){ console.log("error") console.log(response) } }); }, function() {//error var errorInfo = [ "原因不明のエラーが発生しました…。" , "位置情報の取得が許可されませんでした…。" , "電波状況などで位置情報が取得できませんでした…。" , "位置情報の取得に時間がかかり過ぎてタイムアウトしました…。" ]; var errorNo = error.code; var errorMessage = "[エラー番号: " + errorNo + "]\n" + errorInfo[ errorNo ] ; alert( errorMessage ) ; }, { "enableHighAccuracy": true, "timeout":10000 } ); } else { //現在地取得不可能 alert("お使いの端末は現在地が取得出来ません。") } }
hoge_controller.rb
def start @hoge = Hoge.find_by(id: params[:id]) @hoge.longitude = params[:longitude] @hoge.latitude = params[:latitude] if @hoge.save flash[:notice] = "#{@hoge.longitude}#{@hoge.latitude}" redirect_to 'hoge/index' end end
まだ回答がついていません
会員登録して回答してみよう