I have a USA JSON file that I'm using to generate a map. The paths are generating states just fine, but now I'd like to add the state name at the center of each path/state.

Here's an example of JSON file

var usa = {"type": "FeatureCollection",
"features": [{ "type": "Feature", "properties": { "NAME": "Alabama"}, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -88.124658, 30.283640 ]...

I've created States by appending to the SVG I've already created

var allStates = svg.selectAll("path")
  .data(usa.features)
  .enter()
  .append("path")
  .attr("d", path)

And here is where I'm trying to add the state names as text

var allStatesNames = svg.selectAll('text')
  .data(usa.features)
  .enter().append("svg:text")
  .attr("transform", function(d) {
    return "translate(" + path.centroid(d.geometry.coordinates) + ")"; })
  .text(function(d) {return d.properties.NAME})

But I just keep getting this back

<text transform="translate(NaN,NaN)">Virginia</text>

Why am I getting NaN and what should I be using instead?

Thanks in advance for the help!

有帮助吗?

解决方案

So the issue is that path.centroid needs both the type of the shape as well as the coordinates, so you can't just pass in the coordinates. You can actually just pass in the entire feature with d.

Try putting path.centroid(d) in the return of your transform attr and it should work for you. It seems that path.centroid(d.geometry) works as well, but is less correct.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top