Created
June 29, 2017 15:38
-
-
Save denisemauldin/98077edcf2c6fba9f1b5876f9eb16642 to your computer and use it in GitHub Desktop.
d3 v4 topojson clickable 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
<!DOCTYPE html> | |
<style> | |
.counties :hover { | |
fill: red; | |
} | |
.county-borders { | |
fill: none; | |
stroke: #fff; | |
stroke-width: 0.5px; | |
stroke-linejoin: round; | |
stroke-linecap: round; | |
pointer-events: none; | |
} | |
</style> | |
<svg width="960" height="600"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="https://d3js.org/topojson.v2.min.js"></script> | |
<script> | |
var svg = d3.select("svg"); | |
var path = d3.geoPath(); | |
d3.json("https://d3js.org/us-10m.v1.json", function(error, us) { | |
if (error) throw error; | |
svg.append("g") | |
.attr("class", "counties") | |
.selectAll("path") | |
.data(topojson.feature(us, us.objects.counties).features) | |
.enter().append("path") | |
.attr("d", path); | |
// the following block is new, adding JS events | |
let hoverEnabled = false; | |
svg.on('mousedown', x => hoverEnabled = true) | |
.on('mouseup', x => hoverEnabled = false) | |
svg.selectAll('.counties path').on('mouseover', function() { | |
if (hoverEnabled) { | |
this.classList.add('hovered'); | |
} | |
}); | |
svg.append("path") | |
.attr("class", "county-borders") | |
.attr("d", path(topojson.mesh(us, us.objects.counties, function(a, b) { return a !== b; }))); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment