繁体   English   中英

如何将位置坐标从HTML5和javascript传递到Rails控制器和mongodb模型?

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

我正在使用一个Web应用程序,我想在该应用程序中获取用户的当前地理位置坐标(纬度,经度,海拔)。 我将Ruby on Rails与MongoDB(Mongoid)结合使用。 我正在通过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>

在body标签中,我要求用户单击按钮以显示坐标。

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

我要做的是将此位置数据(变量loc)传输到我的模型位置。 蒙皮模型如下

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变量作为参数传递给controller#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”索引时,会发生此错误。

然后我更改了参数以使其漂浮在控制器中,然后再传递给模型,因为我认为来自javascript的坐标是作为字符串传递的。 因此将控制器代码更改为

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

它工作得很好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM