Search code examples
javascriptcssd3.jsgeojsontopojson

D3: Properly Scale and Turn Map Right-Side-Up


I'm trying to add a map to a site in D3 and topoJSON that looks like this:

enter image description here

However, when I generate the map with D3/topoJSON, it appears small and upside-down.

enter image description here

After looking at several other answers (such as Center a map in d3 given a geoJSON object), I tried messing with the projection, but the map generated appears unaffected whenever I change the scale, add a translate, or rotate it.

I downloaded the shapefile here: http://openstreetmapdata.com/data/land-polygons and converted it to topoJSON in mapshaper.

Any thoughts?

A fiddle can be found here: http://jsfiddle.net/r10qhpca/

var margin = {top: 60, right: 40, bottom: 125, left: 100},
      containerWidth = $('.events-section1-graph').width(),
      containerHeight = $('#events .section1').height();  

  var width = containerWidth - margin.left - margin.right,
      height = containerHeight - margin.top - margin.bottom;

  var xScale = d3.scale.linear()
                 .range( [0, width] ),
      yScale = d3.scale.linear()
                 .range( [height, 0] );

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

  var projection = d3.geo.mercator()
                     .scale(5000000)
                     .translate([width / 2, height / 2])
                     .rotate([0, 0, 180]);


  var svg = d3.select('.events-section1-graph')
              .append('svg')
              .attr('width', width + margin.left + margin.right)
              .attr('height', height + margin.top + margin.bottom)
              .append('g')
              .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

  queue().defer(d3.json, 'js/continent.json')
         .await(ready);

  function ready(err, world) {
    if (err) console.warn("Error", err);

    var tj = topojson.feature(world, world.objects.continent);

    var continent = svg.selectAll('.continent-path')
                       .data(tj.features)
                       .enter()
                       .append('path')
                       .attr('class', 'continent-path')
                       .attr('d', path);

Solution

  • The problem is here:

      var path = d3.geo.path()
        .projection(projection);//projection is undefined @ the moment
      var projection = d3.geo.mercator()
        .scale(width)
        .translate([width / 2, height / 2]);
    

    You are creating the projection later and assigning projection into path. Thus undefined gets stored in the projection for the path.

    So the fix is simple

      //first make projection  
      var projection = d3.geo.mercator()
        .scale(width)
        .translate([width / 2, height / 2]);
      //then assign the projection to the path
      var path = d3.geo.path()
        .projection(projection);
    

    Working code here.