2016-08-22 37 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

這樣做!非常感謝。 –