Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active August 19, 2018 09:19
Show Gist options
  • Select an option

  • Save clhenrick/11183924 to your computer and use it in GitHub Desktop.

Select an option

Save clhenrick/11183924 to your computer and use it in GitHub Desktop.
D3JS GeoJSON Scale and Translate
<!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>
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@Seinfeld70
Copy link
Copy Markdown

Seinfeld70 commented Aug 19, 2018

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