JSFiddle - React, Tailwind, and code Playground
by Guill84
HTML
<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>
<!DOCTYPE html>
<meta charset="utf-8">
<svg></svg>
CSS
body {
margin: 0;
}
path {
fill: none;
stroke: red;
stroke-linejoin: round;
}
JavaScript
var pi = Math.PI,
tau = 2 * pi;
var width = Math.max(960, window.innerWidth),
height = Math.max(500, window.innerHeight),
active = d3.select(null);
// Initialize the projection to fit the world in a 1×1 square centered at the origin.
var projection = d3.geoMercator()
.scale(1 / tau)
.translate([0, 0]);
var path = d3.geoPath()
.projection(projection);
var tile = d3.tile()
.size([width, height]);
var zoom = d3.zoom()
.scaleExtent([1 << 11, 1 << 14])
.on("zoom", zoomed)
var svg = d3.select("svg")
.attr("width", width)
.attr("height", height)
.on("mousemove", mousemoved);
var raster = svg.append("g");
var vector = svg.append("g").attr("id", "vector");
function mousemoved() {
//console.log(formatLocation(projection.invert(d3.mouse(this)), d3.zoomTransform(this).k));
}
function formatLocation(p, k) {
var format = d3.format("." + Math.floor(Math.log(k) / 2 - 2) + "f");
return (p[1] < 0 ? format(-p[1]) + "°S" : format(p[1]) + "°N") + " "
+ (p[0] < 0 ? format(-p[0]) + "°W" : format(p[0]) + "°E");
}
var country_labels = svg.append("g").attr("id", "country_labels");
d3.json("https://mbostock.github.io/d3/talk/20111018/world-countries.json", function(collection) {
vector.selectAll("path")
.data(collection.features)
.enter().append("path")
.style("fill", "white")
.style("fill-opacity", 0.5)
.attr("d", path).on("click", clicked);
country_labels.selectAll("text")
.data(collection.features)
.enter().append("text")
.attr("x", function(d){return path.centroid(d)[0];})
.attr("y", function(d){return path.centroid(d)[1];})
.attr("dx", -40)
.text(function(d){console.log(d);return d.properties.name})
.style("fill", "#aeaeaf")
.style("font-size", "15px")
// Compute the projected initial center.
var center = projection([-98.5, 39.5]);
// Apply a zoom transform equivalent to projection.{scale,translate,center}.
svg
.call(zoom)
...