Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I connect coordinate points on a map using d3js?

Tags:

svg

d3.js

I'm having trouble connecting points with a line on a map using d3. I think that I should use d3.svg.line() to create the points - but when I do it, I simply get a very small blob. Please see the link below for a screenshot of what I've been able to accomplish thus far - I want to connect the black dots with a line. Any help would be much appreciated.

Screenshot

  var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height*3 + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var group = svg.selectAll("g")
      .data(data)
      .enter()
      .append("g")

  var projection = d3.geo.mercator().scale(5000).translate([-2000,5900]) 
  var path = d3.geo.path().projection(projection)
  var graticule = d3.geo.graticule()
  var line = d3.svg.line()
      .interpolate("linear")
      .x(function(d) { d.geometry.coordinates[0]; })
      .y(function(d) { return d.geometry.coordinates[1] ; });

      // this returns a parse error 
      // .x(function(d) { return projection(d.geometry.coordinates[0]); })
      // .y(function(d) { return projection(d.geometry.coordinates[1]) ; });

  var area = group.append("path")
      .attr("d", path)
      // .attr("d", line(data))
      .attr("class", "area")

})
like image 787
Aaron Rank Avatar asked Nov 01 '22 02:11

Aaron Rank


1 Answers

You have to pass both components of your coordinate to the d3.geo.mercator object, before taking each one separately as your x and y values. Your 'parse error' should go away if you use

.x(function(d) { return projection([d.lon, d.lat])[0]; })  
.y(function(d) { return projection([d.lon, d.lat])[1]; });

instead. This post has a more complete example: D3 map Styling tutorial III: Drawing animated paths.

Hopefully once you are drawing the lines in the correct projection, they'll appear as you expect.

like image 166
Michael Avatar answered Nov 08 '22 05:11

Michael