Skip to content

Instantly share code, notes, and snippets.

Last active Jan 15, 2022
What would you like to do?
Scale Bar With Zooming
license: gpl-3.0

This block uses d3-geo-scale-bar with d3-zoom to make a map with a scale bar that updates as the user zooms in and out.

<!DOCTYPE html>
body {
display: table;
margin: 0 auto;
svg {
overflow: visible;
.state {
fill: #eee;
stroke: #ccc;
<script src=""></script>
<script src=""></script>
<script src=""></script>
const projection = d3.geoAlbers();
const path = d3.geoPath(projection);
const scaleBar = d3.geoScaleBar()
.tickFormat(d => d)
const zoom = d3.zoom()
.scaleExtent([1, 20])
.on("zoom", event => {
const { transform } = event;
g.attr("transform", transform);
const svg ="body").append("svg");
const g = svg.append("g");
const bar = svg.append("g");
.then(data => {
const geojson = topojson.feature(data, data.objects.ne_50m_admin_1_states_provinces_lakes);
const states = g.selectAll(".state")
.attr("class", "state");
addEventListener("resize", draw);
function draw(){
const width = Math.min(innerWidth, 800);
const height = width * .63;
projection.fitSize([width, height], geojson);
scaleBar.size([width, height]);
zoom.translateExtent([[0, 0], [width, height]]);
.attr("width", width)
.attr("height", height)
.attr("d", path)
.on("mouseover", function(){"stroke", "black").raise();
.on("mouseout", function(){"stroke", "#ccc");
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment