Skip to content

Instantly share code, notes, and snippets.

@curran
Last active March 9, 2019 09:39
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 curran/1c17b0b923d52c0a573d5be3132489c2 to your computer and use it in GitHub Desktop.
Save curran/1c17b0b923d52c0a573d5be3132489c2 to your computer and use it in GitHub Desktop.
d3-tile wrapping
license: MIT
height: 500
scrolling: no
border: yes
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
margin: 0;
}
form {
margin: 20px;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
<form>
<input type="checkbox" name="wrap" id="wrap">
<label for="wrap">Wrap tiles</label>
</form>
<svg></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/d3-array@1.0"></script>
<script src="https://unpkg.com/d3-tile@0.0"></script>
<script>
var pi = Math.PI,
tau = 2 * pi;
var width = 960,
height = 300;
var projection = d3.geoMercator()
.scale(1 / tau)
.translate([0, 0]);
var path = d3.geoPath()
.projection(projection);
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
var raster = svg.append("g");
var scale = height;
loadTiles(this.checked);
d3.select("input#wrap")
.on("change", function() { loadTiles(this.checked); });
function loadTiles(wrap) {
var tiles = d3.tile()
.wrap(wrap)
.size([width, height])
.scale(scale)
.translate([scale / 2, scale / 2])
();
var image = raster
.attr("transform", stringify(tiles.scale, tiles.translate))
.selectAll("image")
.data(tiles, function(d) { return d; });
image.exit().remove();
image.enter().append("image")
.attr("xlink:href", function(d) { return "http://" + "abc"[d.y % 3] + ".tile.openstreetmap.org/" + d.z + "/" + d.x + "/" + d.y + ".png"; })
.attr("x", function(d) { return d.tx; })
.attr("y", function(d) { return d.ty; })
.attr("width", 256)
.attr("height", 256);
}
function stringify(scale, translate) {
var k = scale / 256, r = scale % 1 ? Number : Math.round;
return "translate(" + r(translate[0] * scale) + "," + r(translate[1] * scale) + ") scale(" + k + ")";
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment