Skip to content

Instantly share code, notes, and snippets.

@keerlu
Last active June 25, 2022 09:02
Show Gist options
  • Save keerlu/d9128e307c426613c834 to your computer and use it in GitHub Desktop.
Save keerlu/d9128e307c426613c834 to your computer and use it in GitHub Desktop.
World map - click to change centre of projection

This is a Mercator projection world map where you can click to recentre the projection about any point. More details in a blog post here (general background in full post).

Live version hosted here.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: white;
stroke-width: 0.25px;
fill: gray;
}
.cursor {
fill: red;
pointer-events: none;
}
</style>
<body>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 1000,
height = 500;
var projection = d3.geo.mercator()
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousemove", mousemove)
.on("click", clicked); // set SVG window
var path = d3.geo.path()
.projection(projection); // generate path
var g = svg.append("g");
d3.json("world-110m2.json", function(error, topology) {
g.selectAll("path")
.data(topojson.feature(topology, topology.objects.countries)
.features)
.enter()
.append("path")
.attr("d", path);
});
var cursor = svg.append("circle")
.attr("r", 3)
.attr("class", "cursor");
function mousemove() {
cursor.attr("transform", "translate(" + d3.mouse(this) + ")");
}
function clicked(d) {
var newcentre = d3.mouse(this)
projection.rotate([- projection.invert(newcentre)[0], - projection.invert(newcentre)[1]]);
// Transition to the new projection
g.selectAll("path")
.transition()
.duration(0)
.attr("d", path);
var translate = projection.translate();
// Add point showing new projection centre
svg.append("circle")
.attr("r", 5)
.attr("class", "cursor")
.attr("transform", "translate(" + translate + ")");
}
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
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