Most basic connectionmap in d3.js





This post describes how to connect 2 locations on a map using great circle. Great circle represents the shortes distance between 2 locations. It is the first step to get a connection map.


Connection map section

Steps:

  • First of all, learn how to build a basic background map.

  • Then create a path generator called path. Basically, give it 2 set of coordinates and it will return a list of coordinates all along the great circle between them.

  • If you're not sure, try to add console.log(path(link)) and you will see the svg path that has been generated.

  • Finally it is easy to append a path calling this generator.

  • Try to play with the input data to understand how the great circle shape changes.
<!DOCTYPE html>
<meta charset="utf-8">

<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>

<!-- Create an element where the map will take place -->
<svg id="my_dataviz" width="440" height="300"></svg>

<script>

// The svg
var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

// Map and projection
var projection = d3.geoMercator()
    .scale(85)
    .translate([width/2, height/2*1.3])

// Create data: coordinates of start and end
var link = {type: "LineString", coordinates: [[100, 60], [-60, -30]]} // Change these data to see ho the great circle reacts

// A path generator
var path = d3.geoPath()
    .projection(projection)

// Load world shape
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson", function(data){

    // Draw the map
    svg.append("g")
        .selectAll("path")
        .data(data.features)
        .enter().append("path")
            .attr("fill", "#b8b8b8")
            .attr("d", d3.geoPath()
                .projection(projection)
            )
            .style("stroke", "#fff")
            .style("stroke-width", 0)

    // Add the path
    svg.append("path")
      .attr("d", path(link))
      .style("fill", "none")
      .style("stroke", "orange")
      .style("stroke-width", 7)

})

</script>

Related blocks →