Skip to content

Instantly share code, notes, and snippets.

@vigorousnorth
Last active January 13, 2019 01:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save vigorousnorth/7e075f3cbd44a0cbb55e to your computer and use it in GitHub Desktop.
Labelled graticules
<!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.v3.min.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js"></script>
<script>
var width = 960,
height = 540;
var projection = d3.geo.winkel3()
.scale(160)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule();
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) {
if (d.coordinates[0][0] == d.coordinates[1][0]) {
return (d.coordinates[0][0] < 0) ? -d.coordinates[0][0] + "W" : d.coordinates[0][0] + "E";
}
else if (d.coordinates[0][1] == d.coordinates[1][1]) {
return (d.coordinates[0][1] < 0) ? -d.coordinates[0][1] + "S" : d.coordinates[0][1] + "N";
}
})
.attr("d", path);
svg.selectAll('text')
.data(graticule.lines())
.enter().append("text")
.text(function(d) {
if ((d.coordinates[0][0] == d.coordinates[1][0]) && (d.coordinates[0][0] % 30 == 0)) {return (d.coordinates[0][0]);}
else if (d.coordinates[0][1] == d.coordinates[1][1]) {return (d.coordinates[0][1]);}
})
.attr("class","label")
.attr("style", function(d) { return (d.coordinates[0][1] == d.coordinates[1][1]) ? "text-anchor: end" : "text-anchor: middle"; })
.attr("dx", function(d) { return (d.coordinates[0][1] == d.coordinates[1][1]) ? -10 : 0; })
.attr("dy", function(d) { return (d.coordinates[0][1] == d.coordinates[1][1]) ? 4 : 10; })
.attr('transform', function(d) {
return ('translate(' + projection(d.coordinates[0])[0] + ',' + projection(d.coordinates[0])[1] + ')')
});
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