如何使用d3.js拖动和旋转正交贴图(globe)

问题描述 投票:2回答:1

SetUp:我正在构建一个全球应用程序,以更好地直观地表示世界各地区的数据。它使用topojson构建d3.js来构建几何体。

我正在实施ivyywang here实现的阻力。 (除非你是身份,否则不要迷失在数学函数中:“数学书呆子大师”)

我的项目目前是here

问题:我在地球上正确地投影了地球,并且成功地实现了拖动功能......除了。只要我的光标位于国家/地区的范围内,我就只能单击并拖动地球。如何投影我的SVG,以便整个画布响应我的拖动事件?

相关守则:

首先,我从MySQL请求中获取一些数据并将其存储在countryStattistics中。我通过以下函数运行它以更好地索引它。

var countryStatistics = (returned from mySQL query)

  //this function build dataById[] setting data keyed to idTopo
function keyIdToData(d){
  countryStatistics.forEach(function(d) {
    dataById[d.idTopo] = d;
  });  
}    

 function visualize(statisticalData, mapType){
  //pass arguments each function call to decide what data to viasually display, and what map type to use

var margin = {top: 100, left: 100, right: 100, bottom:100},
    height = 800 - margin.top - margin.bottom, 
    width = 1200 - margin.left - margin.right;

  //a simple color scale to correlate to data
var colorScale = d3.scaleLinear()
  .domain([0, 100])
  .range(["#646464", "#ffff00"])


 //create svg
var svg = d3.select("#map")
      .append("svg")
      .attr("height", height + margin.top + margin.bottom)
      .attr("width", width + margin.left + margin.right)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
        //here I attmpt to fill the svg with a different color.  but it is unresponsive
      .attr("fill", "blue")

正如你在这个代码块的末尾看到的那样,我在SVG元素上调用了.attr(“fill”...但是无法获得要呈现的颜色。这可能与我的光标在这个空间中没有响应的原因有关。

继续...

  //set projection type to 2D map or 3d globe dependinding on argument passed see function below
var projection = setMapType(mapType, width, height);

      //a function to call on visualize() to set projection type for map style.
function setMapType(mapType, width, height) {
  if(mapType === "mercator") {
    let projection = d3.geoMercator()
    .translate([ width / 2, height / 2 ])
    .scale(180)
    return projection;
  }else if (mapType === "orthographic"){
    let projection = d3.geoOrthographic()
    .clipAngle(90)
    .scale(240);
    return projection;
  }

  //pass path lines to projections
var path = d3.geoPath()
  .projection(projection);

  //here I create and call the drag function only when globe projection is displayed elected
if(mapType == "orthographic"){
  var drag = d3.drag()
    .on("start", dragstarted)
    .on("drag", dragged);
    svg.call(drag);
}


  //coordinate variables
var gpos0, 
    o0;

function dragstarted(){
  gpos0 = projection.invert(d3.mouse(this));
  o0 = projection.rotate();  
}

function dragged(){
  var gpos1 = projection.invert(d3.mouse(this));
  o0 = projection.rotate();

  var o1 = eulerAngles(gpos0, gpos1, o0);
  projection.rotate(o1);

  svg.selectAll("path").attr("d", path);
}

  //load in the topojson file
d3.queue()
  .defer(d3.json, "world110m.json")
  .await(ready)  

上述函数指的是计算正交旋转所需的数学函数。你可以在ivyywang的代码块中看到它们在第一个链接的顶部。

function ready (error, data){
    if (error) throw error;
    //output data to see what is happening
  console.log("topojson data: ")
  console.log(data);

    //I suspect there may be an issue with this code. 
  countries = topojson.feature(data, data.objects.countries)
    //bind dataById data into countries topojson variable
  .features.map(function(d) {
    d.properties = dataById[d.id];
    return d
  });

  console.log("countries:")
  console.log(countries)

我怀疑上面的国家变量可能是罪魁祸首,主要是因为我不完全理解这段代码。在这个变量中,我将keyIdToData()处理的countryStatistics数据绑定为我的topojson数据的嵌套对象“properties”。我控制台记录它以查看数据。

  svg.selectAll(".country")
    .data(countries)
    .enter().append("path")
    .attr("class", "country")
    .attr("d", path)

    //make fill gradient depend on data
    .attr("fill", function(countries){
        //if no data, country is grey
      if(countries.properties == undefined){
        return "rgb(100 100 100)";
      }
        //else pass data to colorScale()
      return colorScale(countries.properties.literacy)
    })
    .on('mouseover', function(d) {
        //on hover set class hovered which simply changes color with a transition time
      d3.select(this).classed("hovered", true)
    })
    .on('mouseout', function(d) {
      d3.select(this).classed("hovered", false)
    })
  }
};

最后我们有这个小功能

  //this function build dataById[] setting data keyed to idTopo
function keyIdToData(d){
  countryStatistics.forEach(function(d) {
    dataById[d.idTopo] = d;
  });  
}  

可能性:似乎我的SVG渲染不包括我的空(非国家)区域。可能是我的SVG构造的问题?或者当我改变数据并将dataById附加到我的topojson时,我可能会干扰SVG构造?

感谢你让它成为这个遥远的键盘忍者。有任何想法吗?

javascript d3.js svg drag
1个回答
2
投票

问题

您的鼠标交互仅在父g中绘制路径的位置,而不是两者之间的空间。您应用于子路径的样式会覆盖您应用于g的填充。


看看你有什么,你的变量svg持有g

//create svg
var svg = d3.select("#map")
  .append("svg")
  ...
  .append("g")  // return a newly created and selected g
  ...
  .attr("fill", "blue") // returns same g

对于鼠标交互,g只能与其中存在元素的地方进行交互。对于gfill属性不会直接执行任何操作,它仅适用于表示元素(和动画):

作为一个表现属性,它[fill]可以应用于任何元素,但它只对以下十一个元素有效:<altGlyph><circle><ellipse><path><polygon><polyline><rect><text><textPath><tref><tspan>MDN) )

fill上使用g反而会改变子元素,即你的路径。虽然你直接着色,所以蓝色没有视觉效果:

var g = d3.select("body")
  .append("svg")
  .append("g")
  .attr("fill","orange");
  
// Inherit fill:
g.append("rect")
  .attr("width",50)
  .attr("height",50)
  
// Override inheritable fill:
g.append("rect")
  .attr("x", 100)
  .attr("width",50)
  .attr("height",50)
  .attr("fill","steelblue");
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

您需要创建一个要与之交互的元素,以便在当前没有路径的位置进行拖动。


现在,我认为你不想把整个svg背景变成蓝色,只是全球不属于某个国家的部分。您可以使用geojson球体来完成此操作。从技术上讲,它不是geojson规范的一部分,d3识别出类型覆盖整个行星的geojson(因此它不需要坐标)。在将国家/地区添加到地球之前,添加一个球体,这会为拖动事件提供一个与之交互的元素:

svg.append("path")
  .attr("d", path({type:"Sphere"})
  .attr("fill","blue");

这填补了海洋(和土地),我们可以在这些国家附近。现在,由于球体和国家都是同一个g的一部分,我们可以像现在一样对整个地球实施拖累,但现在没有鼠洞交互不起作用的漏洞。

这是一个快速演示,其中包含正交投影和最基本的拖动功能:

var svg = d3.select("svg").append("g");

var projection = d3.geoOrthographic()
  .translate([250,250])
  
var path = d3.geoPath().projection(projection);

d3.json("https://unpkg.com/world-atlas@1/world/110m.json").then( function(data) {

  var world = {type:"Sphere"}
  
  svg.append("path")
    .datum(world)
    .attr("d", path)
    .attr("fill","lightblue");
    
  svg.selectAll(null)
    .data(topojson.feature(data,data.objects.land).features)
    .enter()
    .append("path")
    .attr("fill","lightgreen")
    .attr("d",path);
  
  
  svg.call(d3.drag()
    .on("drag", function() {
      var xy = d3.mouse(this);
      projection.rotate(xy)
      svg.selectAll("path")
       .attr("d",path);
    }))
  

 
 
 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://unpkg.com/topojson-client@3"></script>

<svg width="500" height="500"></svg>
© www.soinside.com 2019 - 2024. All rights reserved.