2016-01-07 130 views
0

我有一个Rails 4应用程序。我想在谷歌地图街景上显示位置。经度和纬度保存在数据库中,因此只能通过导轨访问。 控制器:如何将rails数据传递给javascript?

@posts.each do |post| 
    markers << post.marker_single_show 
end 

的Javascript:

function addMarker(latLng, map, icon) { 
    if (formMarker !== undefined) { 
    formMarker.setMap(null); 
    } 
    formMarker = new google.maps.Marker({ 
    position: latLng, 
    animation: google.maps.Animation.BOUNCE, 
    title: "localisation", 
    icon: icon 
    }); 
    formMarker.setMap(map); 
    var latlngbounds = new google.maps.LatLngBounds(); 
    latlngbounds.extend(latLng); 
    map.fitBounds(latlngbounds); 
    map.panToBounds(latlngbounds); 
} 

正如你可以看到,使用addMarker功能时,我应提供由轨道控制器rendred经纬度值。 如何将值从rails传递给Javascript?

+1

给人一种代码示例会更有帮助。根据您的前端设置方式,您可能可以在控制器中传入实例变量设置,然后通过类似onclick函数的方式将其传递到Google Maps API。我知道那里也有帮助将数据传递给JS的宝石(对你的问题做一个类似的谷歌搜索)。此外,还有在控制器中传回json的方法。 – someoneHere

回答

2
 app/controllers/some_controller.rb 
    def someMethod 
     @railsVariable = Model.all or Model.find(id) 
     end 
    in its view you can do something like this 

<script> 
    var JavascriptVariable = <%= @railsVariable %>; 
</script> 

希望这将帮助你:)

+0

对于那些出现同样问题的人,我使用@ashwintastic提出的黑客技术,它运行良好。 – nizniz