如何根据纬度/经度绘制D3地图上两点之间的线/链接?

时间:2013-08-10 19:18:45

标签: d3.js maps

我正在尝试创建D3中10个主要NASA设施的地图。我已成功生成美国基地地图,并根据纬度和经度的.csv在每个中心位置附加NASA徽标。但是,我无法弄清楚在地图上的点之间绘制线条/链接/弧线/连接的任何优雅方式。

在下面的代码中,我在GSFC和KSC之间画了一条线(使用'var = places','var = route'和'svg.append(“path”)')但是它在SVG上层,因此它位于徽标的顶部(看起来很糟糕),并且在单击放大状态时不会缩放(或者也可以消失)。我希望能够根据.csv的纬度和经度数据在中心之间绘制链接。

<!DOCTYPE html>
<meta charset="utf-8">
<style>

.background {
  fill: none;
  pointer-events: all;
}

#states {
  fill: #aaaaaa;
}

#states .active {
  fill: #ff0000;
  fill-opacity: .5;
}

#state-borders {
  fill: none;
  stroke: #ffffff;
  stroke-width: 1.5px;
  stroke-linejoin: round;
  stroke-linecap: round;
  pointer-events: none;
}

path.link {
  fill: none;
  stroke: #666666;
  stroke-width: 1.5px;
}

.stroke {
  fill: none;
  stroke: #000;
  stroke-width: 3px;
}

.fill {
  fill: #fff;
}

.graticule {
  fill: none;
  stroke: #777;
  stroke-width: .5px;
  stroke-opacity: .5;
}

.route {
  fill: none;
  stroke: blue;
  stroke-width: 3px;
}

</style>
<body>
    <h2>
      <span>NASA Centers</span>
    </h2>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>

var width = 1000,
    height = 600,
    centered;

var projection = d3.geo.albersUsa()
    .scale(1070)
    .translate([width / 2, height / 2]);

var path = d3.geo.path()
    .projection(projection);

var graticule = d3.geo.graticule();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

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

var places = {
    GSFC: [-76.852587, 38.991621],
    KSC: [-80.650813, 28.524963]
    };

var route = {
  type: "LineString",
  coordinates: [
    places.GSFC,
    places.KSC
  ]
};

var point = svg.append("g")
    .attr("class", "points")
  .selectAll("g")
    .data(d3.entries(places))
  .enter().append("g")
    .attr("transform", function(d) { return "translate(" + projection(d.value) + ")"; });

point.append("text")
    .attr("y", 5)
    .attr("dx", "1em")
    .text(function(d) { return d.key; });

d3.json("us.json", function(error, us) {
    g.append("g")
      .attr("id", "states")
    .selectAll("path")
      .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
      .attr("d", path)
      .on("click", clicked);

    g.append("path")
      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
      .attr("id", "state-borders")
      .attr("d", path);

    d3.csv("nasacenters.csv", function(error, data) {
        g.selectAll("image").data([0])
           .data(data)
           .enter()
           .append("image")
            .attr("xlink:href", "nasalogo.png")
            .attr("width", "30")
            .attr("height", "30")
            .attr("x", function(d) {
                   return projection([d.lon, d.lat])[0]-15;
            })
            .attr("y", function(d) {
                   return projection([d.lon, d.lat])[1]-15;
            })

        svg.append("path")
          .datum(route)
          .attr("class", "route")
          .attr("d", path)
          .style("opacity", 0.5);

    });

});

function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  g.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  g.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

    </script>
  </body>
</html>

.csv文件采用以下格式:

code,center,lat,lon
GSFC,Goddard Space Flight Center,38.991621,-76.852587
KSC,Kennedy Space Center,28.524963,-80.650813
JPL,Jet Propulsion Laboratory,34.200463,-118.176008
DFRC,Dryden Flight Research Center,34.613714,-118.076790
GRC,Glenn Research Center,41.415891,-81.861774
MSFC,Marshall Space Flight Center,34.646554,-86.674368
ARC,Ames Research Center,37.409574,-122.064292
LaRC,Langley Research Center,37.092123,-76.376230
JSC,Johnson Space Center,29.551508,-95.092256
SSC,Stennis Space Center,30.363692,-89.600036

1 个答案:

答案 0 :(得分:26)

我根据您描述的问题略微修改了您的示例:http://bl.ocks.org/erikhazzard/6201948

看起来有三个问题:

  1. 路径在图标之上绘制。要解决此问题,您可以更改向组添加项目的顺序,或将子组添加到主g组,确保添加组的顺序与您希望显示的顺序相匹配。

  2. 缩放地图时,点之间的路径不会缩放。要解决此问题,请确保将所有内容添加到要修改clicked()函数的组中。在这种情况下,您的g群组正在放大,因此如果您将路径直接添加到g群组而不是svg,则路径也会缩放。在提供的示例中,文本也不会放大 - 这是因为它直接添加到SVG而不是正在转换的g组。

  3. 不会自动从数据创建路径。要解决此问题,您可以从数据生成包含LineString对象的数组。例如,

        for(var i=0, len=data.length-1; i<len; i++){
        // (note: loop until length - 1 since we're getting the next
        //  item with i+1)
            links.push({
                type: "LineString",
                coordinates: [
                    [ data[i].lon, data[i].lat ],
                    [ data[i+1].lon, data[i+1].lat ]
                ]
            });
        }
    

    然后,执行标准数据连接模式并将links列表传递给数据。当您将path作为d属性传递时,它会根据每个项目的坐标生成一个很棒的弧:

    // Standard enter / update 
    var pathArcs = arcGroup.selectAll(".arc")
        .data(links);
    
    //enter
    pathArcs.enter()
        .append("path").attr({
            'class': 'arc'
        }).style({ 
            fill: 'none',
        });
    
    //update
    pathArcs.attr({
            //d is the points attribute for this path, we'll draw
            //  an arc between the points using the arc function
            d: path
        })
        .style({
            stroke: '#0000ff',
            'stroke-width': '2px'
        })
    
  4. 在我的示例(http://bl.ocks.org/enoex/6201948)中,我在大弧线路径上添加了一个过渡,以说明如何根据传递给链接对象的坐标对的顺序绘制路径。

    希望有所帮助!