Last active
August 19, 2018 09:19
-
-
Save clhenrick/11183924 to your computer and use it in GitHub Desktop.
D3JS GeoJSON Scale and Translate
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> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>D3 NYC Geo Test</title> | |
</head> | |
<style type="text/css"> | |
body { | |
margin: 0; | |
padding: 0; | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script type="text/javascript"> | |
/* code reused from the following stackoverflow question: | |
http://stackoverflow.com/questions/14492284/center-a-map-in-d3-given-a-geojson-object */ | |
var width = 900, | |
height = 900; | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height) | |
.attr("class", "svg"); | |
// load geojson and do stuff in a callback function... | |
d3.json("nyc_coastline.json", function(error, data){ | |
// console.log the data | |
console.log(data); | |
// create a unit projection | |
var projection = d3.geo.albers() | |
.scale(1) | |
.translate([0,0]); | |
// create a path generator. | |
var path = d3.geo.path() | |
.projection(projection); | |
// compute bounds of a point of interest, then derive scale and translate | |
var b = path.bounds(data), | |
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]; | |
// update the projection to use computed scale and translate.... | |
projection | |
.scale(s) | |
.translate(t); | |
// calculate and draw a bounding box for the geojson | |
svg.append("rect") | |
.attr('width', width) | |
.attr('height', height) | |
.style('stroke', 'black') | |
.style('fill', 'orange'); | |
// draw the svg of both the geojson and bounding box | |
svg.selectAll("path").data(data.features).enter().append("path") | |
.attr("d", path) | |
.style("fill", "red") | |
.style("stroke-width", "1") | |
.style("stroke", "blue") | |
}); | |
</script> | |
</body> | |
</html> |
How do I translate this map?
let path = d3.geoPath()
...
No projection.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the input.
I allow myself to ask the following question :
Lines 43 to 46 ==> is there a way to use dynamic height and width instead of hard-coded values ("var width = 900, height = 900;")
In fact, i'd like to to use the height and width of a specific div like here
#container { width:550px; height:550px; position:fixed; top:0; left:0; aligne:center;
}How do i writte var height and var width in my JS ?
Hope you could understand my question (sorry if i'm not clear i just started coding recently)
Thx for your feedbacks