Skip to content

Instantly share code, notes, and snippets.

@owlfox
Last active October 2, 2019 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owlfox/198b5deaacf59a0495513c6dba239943 to your computer and use it in GitHub Desktop.
Save owlfox/198b5deaacf59a0495513c6dba239943 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mexico</title>
<style>
.boundary {
fill: none;
stroke: #888;
stroke-linejoin: round;
}
svg {
border-style: solid;
border-width: 1px;
border-color: #ccc;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="http://d3js.org/d3.v5.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/topojson@3.0.2/dist/topojson.js"></script>
<script>
const jsonUrl = "https://raw.githubusercontent.com/larsvers/Learning-D3.js-4-Mapping/master/chapter-4/geo-data.json"
const height = 600, width = 900
const projection = d3.geoMercator();
let mexico = null
const geoID = function(d) {
return `c + ${d.properties.ID_1}`;
};
const path = d3.geoPath().projection(projection);
const svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height);
d3.json(jsonUrl).then(function(data) {
const states = topojson.feature(data, data.objects.MEX_adm1);
let b, s, t; //border, scale, translate
//>___<??, “set an initial scale and translation to 1 and [0,0]”
projection.scale(1).translate([0, 0]);
b = path.bounds(states);
s = .9 / 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];
projection.scale(s).translate(t);
const map = svg.append('g').attr('class', 'boundary');
mexico = map.selectAll('path').data(states.features);
mexico.enter()
.append('path')
.attr('d', path)
.attr('id', geoID)
mexico.exit().remove();
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment