如何从HTML5&javascript到我的rails控制器和mongodb模型

how do i pass location coordinate getting from HTML5 & javascript to my rails controller and mongodb model ?

本文关键字:rails 我的 控制器 模型 mongodb javascript HTML5 amp      更新时间:2023-09-26

我正在开发一个web应用程序,我想在其中获取用户的当前地理位置坐标(纬度、经度、海拔高度)。我在MongoDB(mongoid)中使用RubyonRails。我正在通过HTML5和Javascript让用户进行协调。

目前,我正在users/new.html.erb中显示这些坐标,我在new.html.erb的头中放入了一个脚本,例如

<!DOCTYPE html>
<html>
<head>
<script>
function getUserLocation() { 
//check if the geolocation object is supported, if so get position
if (navigator.geolocation)
    navigator.geolocation.getCurrentPosition(displayLocation, displayError);
else
    document.getElementById("locationData").innerHTML = "Sorry - your browser doesn't support geolocation!";
}
function displayLocation(position) { 
//build text string including co-ordinate data passed in parameter
var displayText = "User latitude is " + position.coords.latitude + " longitude is " + position.coords.longitude + " and altitude is " + position.coords.altitude;
var loc = [[position.coords.latitude, position.coords.longitude][position.coords.altitude]]
//display the string for demonstration
document.getElementById("locationData").innerHTML = displayText;
}
</script>
</head>

在身体标签中,我请求用户点击按钮以获得堇青石显示。

<input type="button" value="get location" onclick="getUserLocation()"/>
<div id="locationData">
Location Data
</div>

我想做的是,将这个位置数据(var-loc)传输到我的模型位置。mongoid模型如下

model/place.rb
class Place
  include Mongoid::Document
   belongs_to :user
  embeds_one :location
  index({location: "2dsphere"})
end
model/location.rb
class Location
  include Mongoid::Document
   field :type, type: String
  field :coordinates, type: Array
  embedded_in :place
end

我想知道如何将javascript变量作为参数传递到控制器#new方法,然后传递到我的模型位置,其中位置是嵌入文档。

有人能帮忙吗?

解决了问题。感谢这个答案

在脚本中使用了以下代码

 $.post('/places/create',{lat: position.coords.latitude, 
                            lng: position.coords.longitude, 
                            alt:position.coords.altitude });

和控制器

  def create
      @lng_lat = [params[:lng], params[:lat]]
      @alt = params[:alt]
      @place = Place.create(location:{type:"Point", coordinates:@lng_lat}, height:@alt)
    end

但是,当我使用MongoDB(Mongoid)的地理空间功能时。索引坐标"2dsphere"之后。我收到错误:"失败,错误为16755:"insertDocument::由以下原因引起:16755无法从对象中提取地理键,几何体格式错误?:"当我们对坐标进行"2dsphere"索引时,就会出现此错误。

然后,在将params传递给模型之前,我将其更改为控制器中的float,因为我认为它是从javascript中以字符串形式传递的。因此将控制器代码更改为

 @lng_lat = [params[:lng].to_f, params[:lat].to_f]
  @alt = params[:alt].to_f

它运行得非常好。

相关文章: