|
<!DOCTYPE html> |
|
<html> |
|
|
|
<head> |
|
<meta charset="utf-8"> |
|
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> |
|
<title>Nepal Topographic Contours</title> |
|
|
|
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script> |
|
<script type="text/javascript" src="http://d3js.org/topojson.v1.min.js"></script> |
|
|
|
</head> |
|
|
|
<body> |
|
|
|
</body> |
|
<script type="text/javascript"> |
|
var h = 500, |
|
w = 960; |
|
|
|
// set-up unit projection and path |
|
var projection = d3.geo.mercator() |
|
.scale(1) |
|
.translate([0, 0]); |
|
|
|
var path = d3.geo.path() |
|
.projection(projection); |
|
|
|
// set-up svg canvas |
|
var svg = d3.select("body").append("svg") |
|
.attr("height", h) |
|
.attr("width", w); |
|
|
|
// set-up scale for colour coding contours |
|
var cScale = d3.scale.linear() |
|
.domain([0, 1]); |
|
|
|
// read in topojson of Nepal |
|
d3.json("z_contours_500_clipped.json", function(error, nepal) { |
|
|
|
// first variable is used to centre and scale map to viewport |
|
// could have used the bbox feature (see https://github.com/mbostock/topojson/issues/67) |
|
var bTopo = topojson.feature(nepal, nepal.objects.contours_500_clipped), |
|
topo = bTopo.features; |
|
|
|
// calculate range for colours based on ELVE property |
|
// Note when converting to topojon the default is to REMOVE all properties |
|
// from the input file, you need to use the -p switch. |
|
var hRange = d3.extent(topo, function(d, i) { |
|
return d.properties.ELEV |
|
}); |
|
|
|
cScale.domain(hRange); |
|
|
|
// calculate bounds, scale and transform |
|
// see http://stackoverflow.com/questions/14492284/center-a-map-in-d3-given-a-geojson-object |
|
var b = path.bounds(bTopo), |
|
s = .95 / Math.max((b[1][0] - b[0][0]) / w, (b[1][1] - b[0][1]) / h), |
|
t = [(w - s * (b[1][0] + b[0][0])) / 2, (h - s * (b[1][1] + b[0][1])) / 2]; |
|
|
|
projection.scale(s) |
|
.translate(t); |
|
|
|
svg.selectAll("path") |
|
.data(topo).enter() |
|
.append("path") |
|
.style("fill", "none") |
|
.style("stroke", function(d, i) { |
|
return interp(cScale(d.properties.ELEV)); |
|
}) |
|
.attr("d", path) |
|
.on("mouseover", highlight) // just a little example of what's available in terms of interaction |
|
.on("mouseout", function (d,i) {unhighlight(this,d); |
|
}); |
|
|
|
}); |
|
|
|
// function to interpolate between to colours |
|
// see http://stackoverflow.com/questions/12217121/continuous-color-scale-from-discrete-domain-of-strings |
|
|
|
function interp(x) { |
|
var ans = d3.interpolateLab("#ffffe5", "#004529")(x); |
|
return ans |
|
} |
|
// A simple highlight example |
|
function highlight(x) { |
|
|
|
var s = d3.select(this); |
|
|
|
s.style("stroke", "red"); |
|
|
|
} |
|
function unhighlight(x,y) { |
|
|
|
var old = y.properties.ELEV; |
|
var u = d3.select(x); |
|
|
|
u.style("stroke", function(d, i) { |
|
return interp(cScale(old)); |
|
}) |
|
} |
|
</script> |
|
|
|
</html> |
|
|