Last active
February 6, 2016 12:13
-
-
Save xemoe/226f9ac0997540ad2e1a to your computer and use it in GitHub Desktop.
Load countries map with D3
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
(function() { | |
// | |
// Initial variables | |
// | |
var w,h,div,tooltip,_w,_h; | |
var sizes = d3.scale.linear() | |
.range([4, 400]); | |
var projection = d3.geo.mercator(); | |
var path = d3.geo.path() | |
.projection(projection); | |
var zoom = d3.behavior.zoom() | |
.on("zoom", function() { | |
projection.translate(d3.event.translate) | |
.scale(d3.event.scale); | |
feature.attr("d", path); | |
circle.attr("transform", ctr); | |
}); | |
var fsvg = d3.select(document.body) | |
.append("div") | |
.attr("id", "map") | |
.append("svg"); | |
var feature = fsvg.selectAll("path.feature"); | |
tooltip = tooltip || d3.select(document.body) | |
.append("div") | |
.attr("class", "tooltip"); | |
// | |
// End initial | |
// | |
// | |
// Closure | |
// | |
function ctr(d) { | |
return "translate(" + projection([d.longitude, d.latitude]) + ")"; | |
} | |
function loadmap(error, collection) { | |
feature = feature.data(collection.features) | |
.enter() | |
.append("path") | |
.attr("class", "feature") | |
.on("mousemove", onMouseMoveTT) | |
.on("mouseout", onMouseOutTT); | |
div = div || d3.select(document.body) | |
.append("div") | |
.attr("id", "c"); | |
w = document.body.clientWidth; | |
h = document.body.clientHeight; | |
_w = w; | |
_h = h; | |
projection.scale(w/6.5) | |
.translate([w/2, h/1.6]); | |
zoom.translate(projection.translate()) | |
.scale(projection.scale()) | |
.scaleExtent([h/5, h]); | |
feature.attr("d", path); | |
} | |
// | |
// End closure | |
// | |
// | |
// Tooltips | |
// | |
function onMouseMoveTT(d) { | |
if (!d) { | |
tooltip.style("display", "none"); | |
return ; | |
} | |
if (tooltip.style("display") == "none") { | |
moveToolTip(d, d3.event); | |
var html = ""; | |
html += '<div>' + d.properties.name + '</div>'; | |
tooltip.html(html); | |
tooltip.style("display", "block"); | |
$(this).attr("fill-opacity", "0.8"); | |
} | |
} | |
function onMouseOutTT() { | |
tooltip.style("display", "none"); | |
$(this).attr("fill-opacity", "1"); | |
} | |
function moveToolTip(d, event) { | |
event = event || d3.event; | |
if (d && event) { | |
tooltip | |
.style("top", event.pageY > _h / 2 ? (event.pageY - tooltip.node().clientHeight - 16) + "px" : (event.pageY + 16) + "px") | |
.style("left", event.pageX > _w / 2 ? (event.pageX - tooltip.node().clientWidth - 16) + "px" : (event.pageX + 16) + "px") | |
; | |
} | |
} | |
// | |
// End tooltip | |
// | |
// | |
// Main | |
// | |
d3.json("./json/world-countries.json", loadmap); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment