Last active
February 14, 2018 08:09
-
-
Save Andrew-Reid/9556697440f43f576ed79cd5c445910e to your computer and use it in GitHub Desktop.
Autoscale and center topojson d3v3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.land { | |
fill: #e5e5e5; | |
stroke: #000; | |
stroke-width: 0.2; | |
stroke-opacity: 0.8; | |
} | |
.states { | |
fill: none; | |
stroke: #fff; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="https://d3js.org/queue.v1.min.js"></script> | |
<script src="https://d3js.org/topojson.v1.min.js"></script> | |
<script src="https://d3js.org/d3.geo.projection.v0.min.js"></script> | |
<script> | |
var width = 800; | |
var height = 500; | |
var projection = d3.geo.mercator() | |
.scale(1) | |
.translate([width / 2, height / 2]); | |
var path = d3.geo.path().projection(projection); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
queue() | |
.defer(d3.json, "cairo.json") | |
.await(ready); | |
function ready(error, cairo) { | |
if (error) throw error; | |
// center | |
var x = (cairo.bbox[0] + cairo.bbox[2]) / 2; | |
var y = (cairo.bbox[1] + cairo.bbox[3]) / 2; | |
projection.rotate([-x,-y]); | |
// get scale | |
var b = [ projection([cairo.bbox[0],cairo.bbox[3]]),projection([cairo.bbox[2],cairo.bbox[1]]) ]; | |
var s = 0.95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height); | |
projection.scale(s); | |
// append data | |
svg.selectAll("path") | |
.data(topojson.feature(cairo, cairo.objects.monuments).features) | |
.enter() | |
.append('path') | |
.attr('class', 'land') | |
.attr('d', path); | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment