在rubyonrails中将对象传递给javascript

时间:2022-12-05 16:06:29

My MapsController is

我的MapsController

def show
   @outlet=OUtlet.all
   render 'maps/map'
end

My View page is map.html.erb

我的视图页面是map.html.erb

<% @outlet.each do |product| %>
    <%= product.latitude %>
    <%= product.longitude %>
<% end %>

The result is

结果是

   51.503454  -0.119562  51.499633 -0.124755 51.489633  -0.123755 51.479633  -0.122755

I need to pass the array to .js as below format.

我需要按照以下格式将数组传递给.js。

var markers = [
    [ 51.503454,-0.119562],
    [ 51.499633,-0.124755],
    [ 51.489633,-0.123755],
    [ 51.479633,-0.122755]
];

I tried with some example like javascript_tag, attribute method with no luck. Can anyone help to sort it out.

我尝试了一些例子,比如javascript_tag,属性方法,没有运气。谁能帮忙解决一下吗?

The above format is to plot the marker in google-map.

以上格式是在google-map中绘制标记。

1 个解决方案

#1


0  

You can write a helper method to return a array of latitude and longitude values.

您可以编写一个helper方法来返回一个纬度和经度值数组。

module MapsHelper
  def outlet_lat_lons(outlets)
    lat_lons = []
    outlets.each do |outlet|
      lat_lons << [outlet.latitude, outlet.longitude]
    end
  end 
end

Then in your js code call this helper

然后在你的js代码中调用这个助手

var markers = <%= outlet_lat_lons(@outlets) %>;

#1


0  

You can write a helper method to return a array of latitude and longitude values.

您可以编写一个helper方法来返回一个纬度和经度值数组。

module MapsHelper
  def outlet_lat_lons(outlets)
    lat_lons = []
    outlets.each do |outlet|
      lat_lons << [outlet.latitude, outlet.longitude]
    end
  end 
end

Then in your js code call this helper

然后在你的js代码中调用这个助手

var markers = <%= outlet_lat_lons(@outlets) %>;