Search code examples
javascriptd3.jstopojson

Drawing line between two projected points on map - no line showing - D3.js


I am trying to draw a line between two lat/long points on a US map. I have circles indicating the origin and destination, however when I try to draw the line nothing is appearing. No errors are being thrown.

I'm able to manually draw a line between those points by writing:

  svg.selectAll("line")
      .data(data)
      .enter()
      .append("line")
      .attr("x1", projection(data[0])[0])
      .attr("y1", projection(data[0])[1])
      .attr("x2", projection(data[1])[0])
      .attr("y2", projection(data[1])[1])
      .attr("stroke-width", 1)
      .attr("stroke", "black");

But this isn't a sustainable approach since my dataset will consist of thousands of lat/long pairs.

Hoping someone can point my code in the right direction. I hope I'm close since no errors are being thrown. Or maybe I'm taking a horrible approach to drawing lines between points, in which case someone let me know before I am too far down the rabbit hole. Here is a working Plunker to my code.

Thanks in advance.


Solution

  • Plunker: http://plnkr.co/edit/ooLkR8iec5NKx0Ns1zcD?p=preview

    You seem to understand the data join based on your creation of the circles

    svg.selectAll("circle")
        .data(points).enter()
        .append("circle")
        .attr("cx", function (d) {return projection(d)[0]; })
        .attr("cy", function (d) { return projection(d)[1]; })
    

    There's no reason you cannot do the same for lines.

    svg.selectAll("line")
       .data(data)
       .enter()
       .append("line")
       .attr("x1", d=>projection(d[0])[0])
       .attr("y1", d=>projection(d[0])[1])
       .attr("x2", d=>projection(d[1])[0])
       .attr("y2", d=>projection(d[1])[1])
    

    Notice what i did to the initial data structure, and how I modified it to work with circles vs lines.

    By the way, the attribute d is for the path element only.