Skip to content

Instantly share code, notes, and snippets.

@Fil
Last active October 2, 2016 12:02
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 Fil/38f12149738b8767bb10ad1086ce2db0 to your computer and use it in GitHub Desktop.
Save Fil/38f12149738b8767bb10ad1086ce2db0 to your computer and use it in GitHub Desktop.
Labelled graticules (d3v4) [UNLISTED]
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<!-- A refinement of http://bl.ocks.org/mbostock/3664049 with labeled graticules -->
<style>
.graticule {
fill: none;
stroke: #000;
}
.graticule.outline {
stroke-width: 2px;
}
.label {
font: 300 9px "Helvetica Neue", Helvetica, Arial, sans-serif;
text-anchor: end;
}
</style>
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="http://d3js.org/d3-geo-projection.v1.min.js"></script>
<script>
var width = 960,
height = 480;
var projection = d3.geoWinkel3()
.scale(145)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geoPath()
.projection(projection);
var graticule = d3.geoGraticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.selectAll("path")
.data(graticule.lines())
.enter().append("path")
.attr("class", "graticule line")
.attr("id", function(d) {
var c = d.coordinates;
if (c[0][0] == c[1][0]) {
return (c[0][0] < 0) ? -c[0][0] + "W" : +c[0][0] + "E";
}
else if (c[0][1] == c[1][1]) {
return (c[0][1] < 0) ? -c[0][1] + "S" : c[0][1] + "N";
}
})
.attr("d", path);
svg.selectAll('text')
.data(graticule.lines())
.enter().append("text")
.text(function(d) {
var c = d.coordinates;
if ((c[0][0] == c[1][0]) && (c[0][0] % 30 == 0)) {return (c[0][0]);}
else if (c[0][1] == c[1][1]) {return (c[0][1]);}
})
.attr("class","label")
.attr("style", function(d) {
var c = d.coordinates;
return (c[0][1] == c[1][1]) ? "text-anchor: end" : "text-anchor: middle";
})
.attr("dx", function(d) {
var c = d.coordinates;
return (c[0][1] == c[1][1]) ? -10 : 0;
})
.attr("dy", function(d) {
var c = d.coordinates;
return (c[0][1] == c[1][1]) ? 4 : 10;
})
.attr('transform', function(d) {
var c = d.coordinates;
return ('translate(' + projection(c[0]) + ')')
});
svg.append("path")
.datum(graticule.outline)
.attr("class", "graticule outline")
.attr("d", path);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment