0

我想获取一个数组并将数据加载到 json 对象中,但我不知道该怎么做。

行程控制器

def index
@trips = Trip.all
@markers = Array.new
@trips.each do |trip|
  for marker in trip.markers
    @markers.push(marker)
  end
end

@gmaps_options =
{
  "markers"     => { "data" => '[{ "lng": "-99.9018131", "lat": "31.9685988"},
                                 { "lng": "-102.552784", "lat": "23.634501"},
                                 { "lng": "-122.3667", "lat": "40.5833"},
                                 { "lng": "-121.8356", "lat": "39.7400"}
                                  ]', },
  "polylines"   => { "data" => ' [ [
                     {"lng": -99.9018131, "lat": 31.9685988},
                     {"lng": -102.552784, "lat": 23.634501},
                     ], [
                      { "lng": "-122.3667", "lat": "40.5833"},
                      { "lng": "-121.8356", "lat": "39.7400"}
                      ] ]' }
}

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @trips }
  end 
end

经度和纬度现在是硬编码的,但我想将@markers 加载到经度纬度中,

"lng": @markers[0].longitude, "lat": @markers[0].latitude

这整个数据对象是一个字符串。我必须补充

"lng": + "@markers[0].longitude" + , "lat": + "@markers[0].latitude"

对于每个标记对象,因此以某种骇人听闻的方式在 for 循环中创建一个完整的字符串。我认为必须有更好的方法。

在视图中,使用 gmaps(@gmaps_options) 调用地图

任何帮助将不胜感激。

4

2 回答 2

0

不确定您的应用程序中有什么,但从控制器代码看来,您有关联的模型 Triphas_many :markers

和标记模型有纬度和经度字段。

并且您还想显示所有相关的标记。

现在要在 google-map 上显示引脚,它需要正确的 activerecord 关系记录

所以一种方法是

控制器:

@trips = Trip.pluck(:id)
@markers = Marker.where("trip_id in (?)", @trips)
@gmaps_options = @markers.to_gmaps4rails

看法:

= gmaps("markers" => { data: @gmaps_options })

另一种方法是:

在循环的帮助下形成所有位置的纬度和经度的 json 字符串,并将该字符串传递给视图中的数据,就像您在上面所做的那样,因为.to_gmaps4rails不接受数组。

希望这会对你有所帮助。

谢谢。

于 2013-10-26T17:56:10.903 回答
0

这是使用 gmaps4rails 用于折线的最终代码

def index
@trips = Trip.all
@tripLocation = Trip.pluck(:id)
@markers = Marker.where("trip_id in (?)", @tripLocation)
@gmaps_options = @markers.to_gmaps4rails

@polylines_json = {}
polylines = []

i = 0;
@trips.each do |trip|
  polylines[i] = []
  trip.markers.each do |marker|
    polylines[i] += [{:lng=>marker.longitude.to_f, :lat=>marker.latitude.to_f}]
  end
  i+=1
end

@polylines_json = polylines.to_json

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @trips }
end
end

def show
@trip = Trip.find(params[:id])
@markers = @trip.markers
@gmaps_options = @markers.to_gmaps4rails

@polylines_json = {}
polylines = [] 
polylines[0] = []
  @trip.markers.each do |marker|
    polylines[0] += [{:lng=>marker.longitude.to_f, :lat=>marker.latitude.to_f}]
  end


@polylines_json = polylines.to_json

respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @trip }
end
end
于 2013-11-08T22:52:17.057 回答