d3.js add a label in the center of a path

前端 未结 1 689
名媛妹妹
名媛妹妹 2021-01-20 20:45

how to add a label in the center of path programmatically without using the BBOX method because it does not work with banana shapes

d3.json(\"mapgeo.json\",          


        
相关标签:
1条回答
  • 2021-01-20 21:09

    (I confess that I quite didn't understand what you want to achieve with your code, so, I'm going to address specifically your question's title: "how to add a label in the center of a path").

    D3 have a handy function for locating the center of the path, called path.centroid:

    Returns the projected planar centroid (typically in pixels) for the specified GeoJSON object. This is handy for, say, labeling state or county boundaries, or displaying a symbol map.

    You can use it to position your labels:

    .attr("x", function(d) {
        return path.centroid(d)[0];
    })
    .attr("y", function(d) {
        return path.centroid(d)[1];
    })
    

    Here is a demo with a USA map (just found the code online). I'm locating the center of each path using centroid and labelling it with "foo":

    var width = 500,
        height = 400;
    
    var projection = d3.geoAlbersUsa()
        .scale(700)
        .translate([width / 2, height / 2]);
    
    var path = d3.geoPath()
        .projection(projection);
    
    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);
    
    
    d3.json("https://dl.dropboxusercontent.com/u/232969/cnn/us.json", function(error, us) {
    
    
        svg.selectAll(".state")
            .data(topojson.feature(us, us.objects.states).features)
            .enter().append("path")
            .attr("d", path)
            .attr('class', 'state');
    
        svg.selectAll(".stateText")
            .data(topojson.feature(us, us.objects.states).features)
            .enter().append("text")
            .attr("x", function(d) {
                return path.centroid(d)[0];
            })
            .attr("y", function(d) {
                return path.centroid(d)[1];
            })
            .attr("text-anchor", "middle")
            .attr("font-size", "12px")
            .text("foo")
    
    });
    .state {
      fill: none;
      stroke: black;
    }
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://d3js.org/topojson.v1.min.js"></script>

    0 讨论(0)
提交回复
热议问题