Add the state name as an SVG 'text' element, as a sibling to the 'path'
This commit is contained in:
49
index.js
49
index.js
@@ -48,11 +48,12 @@ function drawMap(world) {
|
||||
const projection = d3.geoMercator().fitSize([mapWidth, mapHeight], world)
|
||||
const path = d3.geoPath().projection(projection);
|
||||
|
||||
// Draw the map
|
||||
svg.selectAll("path")
|
||||
.data(world.features)
|
||||
.enter()
|
||||
.append("path")
|
||||
const states = svg.selectAll("g")
|
||||
.data(world.features)
|
||||
.enter()
|
||||
.append("g");
|
||||
|
||||
states.append("path")
|
||||
.attr("d", path)
|
||||
.attr("class", "state")
|
||||
.attr("fill", d => colorMap[d.properties.name])
|
||||
@@ -60,7 +61,43 @@ function drawMap(world) {
|
||||
.text(d => d.properties.name)
|
||||
.each(function(d) {
|
||||
map1.set(d.properties.name, d3.geoCentroid(d));
|
||||
})
|
||||
});
|
||||
|
||||
states.append("text")
|
||||
.attr("x", d => projection(d3.geoCentroid(d))[0])
|
||||
.attr("y", d => projection(d3.geoCentroid(d))[1])
|
||||
.attr("text-anchor", "middle")
|
||||
.attr("font-size", "12px")
|
||||
.attr("fill", "black")
|
||||
.attr("class", "stateText")
|
||||
.attr("id", d => d.properties.name+"Text")
|
||||
.text(d => d.properties.name);
|
||||
|
||||
// Draw the map
|
||||
// svg.selectAll("path")
|
||||
// .data(world.features)
|
||||
// .enter()
|
||||
// .append("path")
|
||||
// .attr("d", path)
|
||||
// .attr("class", "state")
|
||||
// .attr("fill", d => colorMap[d.properties.name])
|
||||
// .append("title") // Tooltip
|
||||
// .text(d => d.properties.name)
|
||||
// .each(function(d) {
|
||||
// map1.set(d.properties.name, d3.geoCentroid(d));
|
||||
// })
|
||||
// .each(function(d) {
|
||||
// const [x, y] = projection(d3.geoCentroid(d)); // Get centroid
|
||||
//
|
||||
// d3.select(this.parentNode) // Select the parent <svg> or <g> container
|
||||
// .append("text") // Append text immediately after the path
|
||||
// .attr("x", x)
|
||||
// .attr("y", y)
|
||||
// .attr("text-anchor", "middle")
|
||||
// .attr("font-size", "12px")
|
||||
// .attr("fill", "black")
|
||||
// .text(d.properties.name);
|
||||
// });
|
||||
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user