This is the code for Chapter 7, Figure 2 from D3.js in Action showing a hand-crafted GeoJSON object representing the bounding box of Manhatten on a D3 tile map.
The purpose of this figure is to better understand the GeoJSON format, not tile mapping, which is explained in detail later in the chapter.
xxxxxxxxxx
<html>
<head>
<title>D3 in Action Chapter 7 - Example 11</title>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="tile.js" type="text/JavaScript"></script>
</head>
<style>
svg {
height: 500px;
width: 500px;
border: 1px solid gray;
}
.countries {
fill: red;
fill-opacity: .5;
stroke: black;
stroke-width: 1px;
}
</style>
<body>
<div id="viz">
<svg>
</svg>
</div>
<div id="controls" />
</body>
<footer>
<script>
var manhattenBoundingBox = {geometry: {coordinates: [[[-74.0479, 40.8820], [-73.9067, 40.8820], [-73.9067, 40.6829], [-74.0479, 40.6829], [-74.0479, 40.8820]]], type: "Polygon"}, id: 999999, properties:{}, type: "Feature"};
var width = 500,
height = 500;
d3.select("svg").append("g").attr("id", "tiles");
d3.select("svg").append("g").attr("id", "vectors");
var tile = d3.geo.tile()
.size([width, height]);
var projection = d3.geo.mercator()
.scale((1 << 18) / 2 / Math.PI)
.translate([width / 2, height / 2]);
var center = projection([-73.95, 40.7]);
var path = d3.geo.path()
.projection(projection);
var zoom = d3.behavior.zoom()
.scale(projection.scale() * 2 * Math.PI)
.translate([width - center[0], height - center[1]])
.on("zoom", redraw);
d3.select("svg").call(zoom);
projection
.scale(1 / 2 / Math.PI)
.translate([0, 0]);
geoPath = d3.geo.path().projection(projection);
d3.select("#vectors").selectAll("path.countries").data([manhattenBoundingBox])
.enter()
.append("path")
.attr("d", geoPath)
.attr("class", "countries")
.style("fill", "red")
.style("stroke-width", 3)
.style("stroke", "black")
.style("fill-opacity", .25)
redraw();
function redraw() {
var tiles = tile
.scale(zoom.scale())
.translate(zoom.translate())
();
var image = d3.select("#tiles").attr("transform", "scale(" + tiles.scale + ")translate(" + tiles.translate + ")")
.selectAll("image")
.data(tiles, function(d) { return d; });
image.exit()
.remove();
image.enter().append("image")
.attr("xlink:href", function(d) { return "https://" + ["a", "b", "c", "d"][Math.random() * 4 | 0] + ".tiles.mapbox.com/v3/examples.map-zgrqqx0w/" + d[2] + "/" + d[0] + "/" + d[1] + ".png"; })
.attr("width", 1)
.attr("height", 1)
.attr("x", function(d) { return d[0]; })
.attr("y", function(d) { return d[1]; });
projection
.scale(zoom.scale() / 2 / Math.PI)
.translate(zoom.translate());
d3.selectAll("path")
.attr("d", geoPath);
}
</script>
</footer>
</html>
https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js