Built with blockbuilder.org
Last active
July 29, 2017 07:12
-
-
Save areologist/dcb4b546e24dfda5b4cfba57b23d91d3 to your computer and use it in GitHub Desktop.
africa map
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
license: mit |
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> | |
<head> | |
<meta charset="utf-8"> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
body { | |
font-family: "Helvetica Neue", Helvetica, sans-serif; | |
font-size: 14px; | |
color: #333; | |
} | |
#content .info { | |
height: 20px; | |
} | |
#content .map path { | |
fill: #aaa; | |
stroke: #fff; | |
} | |
#content .bounding-box rect { | |
fill: none; | |
stroke: #333; | |
stroke-dasharray: 2,1; | |
} | |
#content .centroid { | |
display: none; | |
} | |
#content .centroid circle { | |
fill: red; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="content"> | |
<div class="info">Hover over a country</div> | |
<svg width="620px" height="600px"> | |
<g class="map"></g> | |
<g class="bounding-box"><rect></rect></g> | |
<g class="centroid"><circle r="4"></circle></g> | |
</svg> | |
</div> | |
<script> | |
// Based on D3 in Depth (http://d3indepth.com/) | |
const projection = d3.geoMercator() | |
.scale(400) | |
.translate([200, 280]) | |
.center([0, 5]); | |
const geoGenerator = d3.geoPath() | |
.projection(projection); | |
const handleMouseover = d => { | |
const pixelArea = geoGenerator.area(d); | |
const bounds = geoGenerator.bounds(d); | |
const centroid = geoGenerator.centroid(d); | |
const measure = geoGenerator.measure(d); | |
d3.select('#content .info') | |
.text(d.properties.name + | |
' (path.area = ' + pixelArea.toFixed(1) + | |
' path.measure = ' + measure.toFixed(1) + ')'); | |
d3.select('#content .bounding-box rect') | |
.attr('x', bounds[0][0]) | |
.attr('y', bounds[0][1]) | |
.attr('width', bounds[1][0] - bounds[0][0]) | |
.attr('height', bounds[1][1] - bounds[0][1]); | |
d3.select('#content .centroid') | |
.style('display', 'inline') | |
.attr('transform', `translate(${centroid})`); | |
}; | |
const update = geojson => { | |
const u = d3.select('#content g.map') | |
.selectAll('path') | |
.data(geojson.features); | |
u.enter() | |
.append('path') | |
.attr('d', geoGenerator) | |
.on('mouseover', handleMouseover); | |
}; | |
// Fetch data | |
d3.json('africa.json', function(err, json) { | |
update(json) | |
}); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment