Landon Tholen Landon Tholen - 1 year ago 74
JSON Question

Implement d3 Click-to-zoom

I'm new to web stuff but even I know this is a stupid question... I still can't figure out what I'm doing wrong though. The code on the site here: seems as if you could copy and paste it into an html document and merely modify the link to the us.json so that it points to the full file path. However, the code merely pulls up a blank page.
The inspection of the page source code on the demo ( )is the exact same as the code provided on the main page. What am I missing to implement this??

<!DOCTYPE html>
<meta charset="utf-8">

.background {
fill: none;
pointer-events: all;

#states {
fill: #aaa;

#states .active {
fill: orange;

#state-borders {
fill: none;
stroke: #fff;
stroke-width: 1.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;

<script src="//"></script>
<script src="//"></script>

var width = 960,
height = 500,

var projection = d3.geo.albersUsa()
.translate([width / 2, height / 2]);

var path = d3.geo.path()

var svg ="body").append("svg")
.attr("width", width)
.attr("height", height);

.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", clicked);

var g = svg.append("g");

d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
if (error) throw error;

.attr("id", "states")
.data(topojson.feature(us, us.objects.states).features)
.attr("d", path)
.on("click", clicked);

.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("id", "state-borders")
.attr("d", path);

function clicked(d) {
var x, y, k;

if (d && centered !== d) {
var centroid = path.centroid(d);
x = centroid[0];
y = centroid[1];
k = 4;
centered = d;
} else {
x = width / 2;
y = height / 2;
k = 1;
centered = null;

.classed("active", centered && function(d) { return d === centered; });

.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
.style("stroke-width", 1.5 / k + "px");


Answer Source

Download the us.json file and put it in the same directory as your index.html. Then change the path to the us.json file:

d3.json("us.json", function(error, us) {

This worked for me. If you are using Chrome and accessing the index.html file on your local computer, not from a remote webserver, you will need to run a local webserver for this to work. If you just try to open the index.html file in Chrome, it won't display properly due to Chrome's local file restrictions. It needs to be accessed through a webserver.

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download