Weedoze
Weedoze

Reputation: 13943

D3JS - Label box over a circle

I am displaying multiple circles over a map and I need to add a label that will display a certain value. This should look like this circle label The red line is not necessary

What I have now is current circle label

The problem is that if the number inside is big, it will be written outside of the bounds of the rectangle. How can I manage this ? How can the width of the rectangle be proportionnal to the size of the value inside ?

Javascript

//circle
data.append("circle")
    .attr("class", "station")
    .attr("r", 5)
    .attr("cx", function(d) {
        return (d.coordinates.x + 5000) / 450;
    })
    .attr("cy", function(d) {
        return (-d.coordinates.y + 170000) / 450;
    })
    .style("stroke-width", .5)
    .style("cursor", "pointer");
//box
data.append("rect")
    .attr("width", 10)
    .attr("height", 10)
    .attr("x", function(d) {
        return ((d.coordinates.x + 5000) / 450 - 2);
    })
    .attr("y", function(d) {
        return ((-d.coordinates.y + 170000) / 450 - 10);
    })
    .attr("fill", "white");
//text
data.append("text")
    .attr("x", function(d) {
        return ((d.coordinates.x + 5000) / 450 + 2);
    })
    .attr("y", function(d) {
        return ((-d.coordinates.y + 170000) / 450 - 2);
    })
    .style("font-size", "1.3 em")
    .attr("text-anchor", "middle")
    .text(function(d) {
        return d.value;
    })
    .style("cursor", "pointer");

Upvotes: 1

Views: 56

Answers (1)

Tim B
Tim B

Reputation: 1983

You need to set the width value to depends on your label length

data.append("rect")
.attr("width", function(d) {
    return 10 + 5 * d.value.length; // 10 and 5 are arbitrary values
})

Upvotes: 1

Related Questions