Skip to content

Instantly share code, notes, and snippets.

@almccon
Last active April 25, 2021 12:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save almccon/a53831a573911d0a875821c5f9fac6be to your computer and use it in GitHub Desktop.
Save almccon/a53831a573911d0a875821c5f9fac6be to your computer and use it in GitHub Desktop.
d3 loading GeoJSON + mouse interaction
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: #ccc;
stroke: #fff;
stroke-width: .5px;
}
circle {
fill: #fff;
fill-opacity: 0.4;
stroke: #111;
}
path.active {
fill: pink;
}
circle.active {
fill: blue;
}
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script src="//d3js.org/d3.geo.projection.v2.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geoMercator();
var path = d3.geoPath()
.projection(projection)
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var url = "http://enjalot.github.io/wwsd/data/world/world-110m.geojson";
var url2 = "http://enjalot.github.io/wwsd/data/world/ne_50m_populated_places_simple.geojson"
d3.json(url, function(error, countries) {
d3.json(url2, function(error, places) {
if (error) console.log(error);
console.log("geojson", countries, places);
svg.selectAll("path")
.data(countries.features)
.enter().append("path")
.attr("d", path)
.on("mouseover",function(d) {
console.log("just had a mouseover", d3.select(d));
d3.select(this)
.classed("active",true)
})
.on("mouseout",function(d){
d3.select(this)
.classed("active",false)
})
svg.selectAll("circle")
.data(places.features)
.enter().append("circle")
.attr('r',5)
.attr('cx',function(d) { return projection(d.geometry.coordinates)[0]})
.attr('cy',function(d) { return projection(d.geometry.coordinates)[1]})
.on("mouseover",function(d) {
console.log("just had a mouseover", d3.select(d));
d3.select(this)
.classed("active",true)
})
.on("mouseout",function(d){
d3.select(this)
.classed("active",false)
})
})
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment