Skip to content

Instantly share code, notes, and snippets.

@memandip
Last active August 28, 2018 06:12
Show Gist options
  • Save memandip/4099a13de1f971dd15122b7b4878e2a9 to your computer and use it in GitHub Desktop.
Save memandip/4099a13de1f971dd15122b7b4878e2a9 to your computer and use it in GitHub Desktop.
create map with topojson and zoom map with d3 v5
let width = 850, height = 345;
let projection = d3.geoMercator();
let path = d3.geoPath().projection(projection);
let svg = d3.select("#map-wrapper").append("svg")
.attr('id', 'map')
.attr("width", '100%')
.attr("height", height)
let g = svg.append('g');
let div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.json("topjson_file_path").then(function (data) {
let featureData = topojson.feature(data, data.objects['data_key_name'])
let datas = featureData.features;
projection.scale(1).translate([0, 0]);
let b = path.bounds(featureData),
s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height),
t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2];
projection
.scale(s)
.translate(t);
g.selectAll("path")
.data(datas)
.enter()
.append("path")
.attr("d", path);
let zoom = d3
.zoom()
.scaleExtent([.8, 20])
.on("zoom", function () {
g.attr("transform", d3.event.transform);
});
svg.call(zoom)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment