I'd like to add a neighborhood name to each of the neighborhoods in my d3 map.
I used the centroid() function in this code.
var mapLabel = svg.selectAll("text")
.data(json)
.enter()
.append("text")
.text(function (d) {
return d.properties.nhood;
})
.attr('transform', function (d) {
return 'translate(' + path.centroid(d) + ')';
})
.attr('font-size', '6pt');
And it puts the names of each of the neighborhoods far from the center.
I tried with this code too.
function addText(p)
{
var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
var b = p.getBBox();
t.textContent = "a";
t.setAttribute("transform", "translate(" + (b.x + b.width/2) + " " + (b.y + b.height/2) + ")");
t.setAttribute("fill", "red");
t.setAttribute("font-size", "14");
p.parentNode.insertBefore(t, p.nextSibling);
}
var paths = document.querySelectorAll("path");
for (var p in paths)
{
addText(paths[p])
}
The code worked to add text to the center of each SVG, but I don't know how to get it to add custom text for each neighborhood. Instead, I get "a" forty-one times.
I was also trying around with getBBox(). I couldn't access the function, I ran into the getBBox() is not a function
error.
This is the section of code that creates the map.
var projection = d3.geoIdentity()
.reflectY(true)
.fitSize([w, h], jsonClone)
var pathFlipped = d3.geoPath()
.projection(projection);
const mapSelection = svg.selectAll("path")
.data(json)
mapSelection
.enter()
.append("path")
.attr("d", pathFlipped)
.style("fill", "lightgrey")
var mapLabel = svg.selectAll("text")
.data(json)
.enter()
.append("text")
.text(function (d) {
return d.properties.nhood;
})
.attr('transform', function (d) {
return 'translate(' + path.centroid(d) + ')';
})
.attr('font-size', '6pt');
This is a demo of the full map.