Reputation: 449
I try to draw a map thank to d3 and topojson. Then I draw each country one by one with this code :
d3.json("datamaps-0.5.0/src/js/data/world.topo.json", function(error, map) {
console.log(map);
for (i=0; i<map.objects.world.geometries.length; i++)
{
svg.append("path")
.attr("class", "state")
.datum(topojson.feature(map, map.objects.world.geometries[i]))
.attr("d", path);
}
});
Although the code works well, I'm looking for a more elegant way than a loop to draw a such map...
Upvotes: 0
Views: 914
Reputation: 2100
One way to do it is to first compute your data array, then map it to the paths with d3
var features= map.objects.world.geometries
.map( //.map: create a new array by applying the function below to each element of the orignal array
function(g) { //take the geometry
return topojson.feature(map, g) //and return the corresponding feature.
}
);
svg.selectAll(".state")
.data(features)
.enter()
.append("path")
.attr("class", "state")
.attr("d", path);
This should be exactly equivalent to your code.
Upvotes: 1