2016-12-27 75 views
1

如何添加在路中心的标签编程,而不使用BBOX方法,因为它不与香蕉形状的工作d3.js在路的中心添加标签

d3.json("mapgeo.json", function(json) { 
       //Bind data and create one path per GeoJSON feature 
       paths =  g.selectAll("path") 
          .data(json.features) 
          .enter() 
          .append("path") 
          .attr('name', function(d) { 
           return d.properties.name.toLowerCase(); 
          }) 
          .attr("d", path) 
          .attr("id", function(d, i) { return 'polygon'+i;}) 
          .style("fill", "steelblue"); 
    for(var i=0;i<paths[0].length;i++){ 
     var pp = paths[0][i].__data__.properties; 
     svg 
     .append('text') 
     .attr("x", 145) 
     .attr("dy", 105) 
    .append("textPath") 
    .attr("xlink:href","#polygon"+i) 
     .text(paths[0][i].__data__.properties.temperature+' C°'); 
    } 
    }); 

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 
<svg width="400" height="300"> 
 
<g> 
 
<path name="cf40" d="M590.3383838385344,295.20151514932513 C 756 327,756 327, 878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;" transform="translate(-500,-260)"></path> 
 
</g> 
 
<text x="145" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text> 
 
</svg>

+0

哪里是你的D3代码?我看到的只是SVG定义。 –

+0

@TudorCiotlos ijust编辑过,你现在可以看到代码。 –

回答

0

(我承认我挺不理解你要实现你的代码是什么,所以,我要解决的具体问题的标题:“如何在一个中心添加标签路径“)。

D3具有用于定位所述路径的中心一个方便的功能,称为path.centroid

返回投影平面质心(通常以像素为单位)为指定GeoJSON的对象。这对标记州或县边界或显示符号图很方便。

你可以用它来定位您的标签:

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

这是一个带美国地图(刚发现的代码在线)演示。我使用定位每个centroid路的中心,并与“富”诬指:

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>