I have a JSON file with a number of coordinates, like so:
[
{
"coord": [
184.5247050,
775.2556777
]
},
{
"coord": [
177.4747474,
833.2566478
]
},
{
"coord": [
255.6434553,
446.7733333
]
}
]
I use this code with the d3
library, to try to plot the data on a canvas:
var svg = d3.select("#canvas");
d3.json(location_data, function(data){
svg.selectAll("circle")
.data(data.coord)
.enter()
.append("circle")
.attr("cx", function(element, index){
return index;
})
.attr("cy", function(element, index){
return index;
})
.attr("r", 30)
.attr("fill", "lightgreen");
})
But I do not see any output. What is wrong with the code? How do I fix it?
The problem is that you bind the data using .data(data.coord)
, but data is an array and has no coord attribute. You have to transform your object array to an array containing arrays of coordinates like so:
.data(data.map(d => d.coord))
You probably also need to change the way you set "cx" and "cy" attributes:
.attr("cx", d => d[0])
.attr("cy", d => d[1])
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.