Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
d3-composite-projections test
border:none
height:700

Test with d3-composite-projection and preprojected TopoJSON

<!DOCTYPE html> <svg></svg>
<script src="https://unpkg.com/d3-composite-projections"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/topojson.v3.min.js"></script>
<style>
#info {
top: 0;
left: 0;
position: absolute;
padding: 1rem;
font-family: sans-serif;
}
#info.error {
color: brown;
}
#error {
margin-top: 0.5rem;
font-weight: bold;
visibility: hidden;
}
path {
fill: none;
}
</style>
<div id="info">
<div id="coords"></div>
<div id="error">Error</div>
</div>
<script>
const margin = { top: 20, right: 20, bottom: 20, left: 20 },
width = window.innerWidth - margin.left - margin.right,
height = width * 0.8 - margin.top - margin.bottom;
const info = d3.select("#info");
const error = d3.select("#error");
const svg = d3
.select("svg")
.attr("width", width)
.attr("height", height);
d3.json("https://unpkg.com/es-atlas@0.2.0/es/autonomous_regions.json")
.then(es => {
const projection = d3
.geoConicConformalSpain()
.fitSize(
[width - margin.left - margin.right, height],
topojson.feature(es, es.objects.autonomous_regions)
);
const path = d3.geoPath(projection);
svg
.append("path")
.datum(topojson.feature(es, es.objects.autonomous_regions))
.attr("d", d => path(d))
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-linejoin", "round");
svg
.append("path")
.attr("d", projection.getCompositionBorders())
.attr("fill", "none")
.attr("stroke", "brown")
.attr("stroke-dasharray", "10 5");
const coords = [];
svg.on("mousemove", function() {
const data = projection.invert(d3.mouse(this));
d3.select("#coords").html(data);
if (projection(data)) {
coords.push(data);
info.classed("error", false);
error.style("visibility", "hidden");
update();
} else {
info.classed("error", true);
error.style("visibility", "visible");
}
});
function update() {
svg
.selectAll("circle")
.data(coords)
.enter()
.append("circle")
.attr("cx", function(d) {
return projection(d)[0];
})
.attr("cy", function(d) {
return projection(d)[1];
})
.attr("opacity", 0.5)
.attr("stroke", 1)
.attr("fill", "brown")
.attr("r", 5)
.transition()
.attr("r", 2);
}
})
.catch(err => console.warn(err));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.