2016-08-22 33 views
0

我想包括地图,我在D3上作出提示,模仿此代码: http://bl.ocks.org/lhoworko/7753a11efc189a936371地图提示

这里是我工作的地图: https://pantherfile.uwm.edu/schro333/public/2016_electoral_map/

正如你在这里看到的,我有工具提示工作,并且当用户悬停在一个状态上时它们显示正确的名字,但是相对于光标的位置确实是关闭的。我不确定这是为什么。

相关代码:

 svgContainer.selectAll("pathCodes") 
      .data(json.features) 
      .enter() 
      .append("path") 
      .attr("id", 
       function(d){ 
        var stateNameId = d.properties.name.toString(); 
        stateNameId = stateNameId.replace(/\s+/g, ''); 
        return stateNameId; 
      }) // this function returns the name of the state with spaces stripped and assigns it to individual polygon as id 
      .attr("d", pathCodes) 
      .attr("stroke", "black") // state outline color 
      .attr("stroke-width", "1") // state outline width 
      .attr("class", "noparty") // default to no party 
      .style("fill", politicalParties[0].color) // default fill is that of no party 
      ///////////// 
      .on('mousemove', function(d) { 
       var mouse = d3.mouse(svgContainer.node()); 
       tooltip.classed('hidden', false) 
        .attr('style', 'left:' + (mouse[0]) + 
          'px; top:' + (mouse[1]) + 'px') 
        .html(d.properties.name); 
      }) 
      .on('mouseout', function() { 
       tooltip.classed('hidden', true); 
      }); 
      ///////////// 

回答

1

你得到了错误的位置,因为你使用的是X/Y位置是基于关闭SVG,而不是在页面上SVG的实际位置。

您可以使用

var loc = document.getElementById("states-map").getBoundingClientRect(); 
console.log(loc.top); //add this to the top 

得到补偿。不确定d3的方式来做到这一点。

+0

这样做!非常感谢。 –