2017-10-12 85 views
1

我已经在d3中创建了一张地图,并且需要在其中添加一系列圆圈。我试图得到一个圆圈来展示和不能。我也改变了圈子的大小。开发工具在页面上显示一个圆圈,但不会显示。这是我的代码:将圆圈追加到d3中的地图

该圆圈放置在地图的中心。

var features = parsedJSON.features; 

mapLayer.selectAll('path') 
    .data(features) 
    .enter().append('path') 
    .attr('d', path) 
    .attr('vector-effect', 'non-scaling-stroke') 
    .attr('fill', '#e8edfc') 
    .select('svg').enter() 
    .append('circle') 
    .attr('cx',-106.661513) 
    .attr('cy', 35.05917399) 
    .attr('r','10px') 
    .style('fill', 'red');  

回答

-1

您正在追加一个圆到一个路径元素,这是无法在SVG中完成的。更好的做法是创建每个功能的一组元素(“G”),并追加路径,圆圈等来的是,例如上面的代码应该是:

let feature = mapLayer.selectAll('.path') 
     .data(features) 
     .enter() 
     .append('g') 

    feature.append('path) 
     .attr('d', path) 
     .attr('vector-effect', 'non-scaling-stroke') 
     .attr('fill', '#e8edfc') 

    feature.append('circle') 
     .attr('cx',-106.661513) 
     .attr('cy', 35.05917399) 
     .attr('r','10px') 
     .style('fill', 'red'); 

如果要添加多个圈子,你将需要改变分配CX,CY的部分,和r使用附加的数据,例如

feature.append('circle') 
      .attr('cx', function(d) { return xScale(d.value); }) 
      etc 
+0

纠正错误,在我的示例代码 –

+0

谁downvoted这可能做的理由很简单:有多少圈,你认为你的代码附加(右一个比其他)? –

+0

我回答了手头的问题:)“我试图让一个圆圈显示,但不能。” –

1

首先,你cxcy值...

.attr('cx',-106.661513) 
.attr('cy', 35.05917399) 

...似乎并不是实际的SVG坐标,而是经度和纬度而不是。在这种情况下,你必须使用你的投影(在这里我假设它被命名为projection):

.attr('cx', projection([-106.661513, 35.05917399])[0]) 
.attr('cy', projection([-106.661513, 35.05917399])[1]) 

其次,你可以不是圆形附加到路径。用你的mapLayer的选择:

mapLayer.append("circle") 
    .attr('cx', projection([-106.661513, 35.05917399])[0]) 
    .attr('cy', projection([-106.661513, 35.05917399])[1]) 
    .attr('r','10px') 
    .style('fill', 'red');