A demo of d3-tile when projecting to fit a bounding box.
Tiles copyright OpenStreetMap contributors.
forked from mbostock's block: Tile by Bounding Box
xxxxxxxxxx
<meta charset="utf-8">
<style>
svg,
#tiles {
position: absolute;
width: 960px;
height: 600px;
overflow: hidden;
}
img { border: 1px dashed red}
</style>
<div id="tiles"></div>
<svg width="960" height="480"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script src="//d3js.org/d3-tile.v0.0.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var tilesg = svg.append('g').attr('id', 'tiles');
var projection = d3.geoMercator();
var feature = {
type: "LineString",
coordinates: [[1, 47.7],[1.2, 47.9]]
}
projection.fitExtent([[10,10],[width-10,height-10]], feature);
// see https://bl.ocks.org/mbostock/4150951 for a related example.
var tiles = d3.tile()
.size([width, height])
.scale(projection.scale() * 2 * Math.PI)
.translate(projection.translate())
();
tilesg
.selectAll("image").data(tiles).enter().append("image")
.attr("xlink:href", function(d, i) {
// return `https://map${1 + (d[1] % 3)}.vis.earthdata.nasa.gov/wmts-webmerc/VIIRS_CityLights_2012/default/GoogleMapsCompatible_Level8/${d[2]}/${d[0]}/${d[1]}.jpg`;
return `https://${"abc"[d[1] % 3]}.tile.openstreetmap.org/${d[2]}/${d[0]}/${d[1]}.png`;
"https://" + "abc"[d[1] % 3] + ".tile.openstreetmap.org/" + d[2] + "/" + d[0] + "/" + d[1] + ".png";
})
.attr('transform', d => `translate(${tiles.translate.map((x,i) => (d[i] + x) * tiles.scale)})`)
.attr("width", tiles.scale)
.attr("height", tiles.scale);
d3.json("https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/us.json", function(error, us) {
if (error) throw error;
svg.append("path")
.datum(topojson.mesh(us, us.objects.states))
.attr("d", d3.geoPath().projection(projection))
.attr("fill", "none")
.attr("stroke", "#000");
svg.append("path")
.datum(feature)
.attr("d", d3.geoPath().projection(projection))
.attr("fill", "none")
.attr("stroke-width", "3")
.attr("stroke", "green");
});
function floor(k) {
return Math.pow(2, Math.floor(Math.log(k) / Math.LN2));
}
</script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-tile.v0.0.min.js
https://d3js.org/topojson.v1.min.js