When zooming a map with d3-zoom, update the scale bar created with d3-geo-scale-bar to reflect the current zoom.
xxxxxxxxxx
<html>
<head>
<style>
body {
margin: 0;
}
svg {
margin: 0 auto;
display: table;
}
path {
fill: #eee;
stroke: #ddd;
vector-effect: non-scaling-stroke;
}
</style>
</head>
<body>
<script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<script src="https://d3js.org/d3-transition.v1.min.js"></script>
<script src="https://d3js.org/d3-zoom.v1.min.js"></script>
<script src="https://d3js.org/d3-drag.v1.min.js"></script>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="india.js"></script>
<script src="https://unpkg.com/d3-geo-scale-bar@1"></script>
<script>
let width, height;
const svg = d3.select("body").append("svg");
const g = svg.append("g");
const polygon = g.append("path").datum(india);
const projection = d3.geoMercator();
const path = d3.geoPath().projection(projection);
const miles = d3.geoScaleBar()
.units(d3.geoScaleMiles)
.left(.5)
.top(.1)
.distance(500);
const scaleBarMiles = svg.append("g");
const kilometers = d3.geoScaleBar()
.left(.5)
.top(.1)
.distance(800);
const scaleBarKilometers = svg.append("g")
.attr("transform", "translate(0, 40)")
.append("g");
const zoom = d3.zoom()
.scaleExtent([1, 10])
.translateExtent([[0, 0], [width, height]])
.on("zoom", _ => {
const t = d3.event.transform;
g.attr("transform", t);
miles.zoomFactor(t.k);
scaleBarMiles.call(miles);
kilometers.zoomFactor(t.k);
scaleBarKilometers.call(kilometers);
});
redraw();
window.onresize = _ => redraw();
function redraw(){
width = window.innerWidth;
height = Math.min(width * 1.12, window.innerHeight);
svg.attr("width", width).attr("height", height);
projection.fitSize([width, height], india);
polygon.attr("d", path);
miles.size([width, height]).projection(projection);
scaleBarMiles.call(miles);
kilometers.size([width, height]).projection(projection);
scaleBarKilometers.call(kilometers);
zoom.translateExtent([[0, 0], [width, height]]);
svg.call(zoom);
}
</script>
</body>
</html>
https://d3js.org/d3-dispatch.v1.min.js
https://d3js.org/d3-selection.v1.min.js
https://d3js.org/d3-transition.v1.min.js
https://d3js.org/d3-zoom.v1.min.js
https://d3js.org/d3-drag.v1.min.js
https://d3js.org/d3-array.v1.min.js
https://d3js.org/d3-geo.v1.min.js
https://unpkg.com/d3-geo-scale-bar@1