Skip to content

Instantly share code, notes, and snippets.

@miroli
Last active August 29, 2015 14:21
Show Gist options
  • Save miroli/fce450596f3ad558e4f7 to your computer and use it in GitHub Desktop.
Save miroli/fce450596f3ad558e4f7 to your computer and use it in GitHub Desktop.
D3 raster bounds
var svg;
d3.json('bounds.json', function(bounds) {
window.bounds = bounds;
initMap();
});
function initMap() {
var map = d3.select('#map'),
width = $('#map').width(),
height = $('#map').height();
var projection = d3.geo.mercator()
.scale(1)
.translate([0, 0]);
var path = d3.geo.path()
.projection(projection);
svg = map.append('svg')
.attr('width', width)
.attr('height', height);
zoom_projection(projection, path, bounds, width, height);
svg.selectAll('.bbox')
.data(bounds.features)
.enter().append('path')
.attr('class', 'bbox')
.attr('d', path);
}
function zoom_projection(projection, path, bounds, width, height) {
var b = path.bounds(bounds),
s = 1 / 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];
projection
.scale(s)
.translate(t);
}
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.
<!DOCTYPE html>
<html>
<head>
<title>D3 raster bounds</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="map">
</div>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="app.js"></script>
</body>
</html>
#map {
background-image: url('background.jpg');
background-size: cover;
height: 291px;
width: 437px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment