简体   繁体   中英

Rails won't render json data on leaflet with d3

Using Rails 4, Leaflet(with leaflet-rails gem), d3 (with d3-rails gem), This line works, the map renders, data points all show up.

<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>

When passing the data in an instance variable from the controller this does not work:

<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>

Any suggestions?

The first parameter for d3.json should be the url to the json data, which means this function will load the data dynamically based on the url you give in the format of a string.

d3.json(url[, callback])

I think what you are trying to do is render some data you got from the controller. That way you don't need to use d3.json to load the data. Instead, you can just put the data inside the erb template:

    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)
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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