Skip to content

Instantly share code, notes, and snippets.

@espinielli
Last active February 15, 2016 10:39
Show Gist options
  • Save espinielli/2b80554d2de01a2c0b80 to your computer and use it in GitHub Desktop.
Save espinielli/2b80554d2de01a2c0b80 to your computer and use it in GitHub Desktop.
Scale and translate for D3 maps

When you want to plot a map you have to find out which scale and translation is needed for it to fit your plotting area.

The answer to this comes from Mike Bostok on SO:

http://stackoverflow.com/questions/14492284/#answer-14691788

The code below prints the relevant scale/translate values given the projection and bounding box of your map:

// from http://stackoverflow.com/questions/14492284/#answer-14691788
var projection = d3.geo.azimuthalEqualArea()
    .scale(1)
    .translate([0,0])
    .clipAngle(180 - 1e-3)
    .precision(0.1);
var path = d3.geo.path()
    .projection(projection);

var N = 71,
    E = -11,
    W = 35,
    S = 34,
    bbox = { "type": "Polygon",
    "coordinates": [
      [
        [E, N],
        [W, N],
        [W, S],
        [E, S]
      ] ]
    };

// find proper scale and translation from bounds of bbox polygon
var b = path.bounds(bbox),
    s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
    t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];

console.log("scale="+s);
console.log("translate="+t);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment