Rails不会使用d3在传单上呈现json数据

时间:2014-09-01 14:45:31

标签: ruby-on-rails json d3.js leaflet

使用Rails 4,Leaflet(带有leaflet-rails gem),d3(带有d3-rails gem), 此行有效,地图呈现,数据点全部显示。

<script>
....
d3.json("../map_data.json", function(collection) {
        /* Add a LatLng object to each item in the dataset */
        collection.features.forEach(function(d) {
            d.LatLng = new L.LatLng(latitude,longitude)
        })
....
</script>

从控制器传递实例变量中的数据时,这不起作用:

<script>
....
d3.json(<%= @map_data %>, function(collection) {
        /* Add a LatLng object to each item in the dataset */
        collection.features.forEach(function(d) {
            d.LatLng = new L.LatLng(latitude,longitude)
        })
....
</script>

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

d3.json的第一个参数应该是json数据的url,这意味着这个函数将根据你给出的字符串格式动态加载数据。

d3.json(url[, callback])

我认为你要做的是渲染你从控制器获得的一些数据。这样您就不需要使用d3.json来加载数据。相反,您可以将数据放在erb模板中:

    var collection = <%= @map_data.to_json.html_safe %>
    /* Add a LatLng object to each item in the dataset */
    collection.features.forEach(function(d) {
        d.LatLng = new L.LatLng(latitude,longitude)
    })