javascript-d3How can I create a map using JavaScript and D3?
Creating a map using JavaScript and D3 is relatively straightforward. Here is an example code block to get started:
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.append("g");
d3.json("https://d3js.org/us-10m.v1.json", function(error, us) {
if (error) throw error;
g.append("g")
.attr("id", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", d3.geoPath());
g.append("path")
.attr("id", "state-borders")
.attr("d", d3.geoPath(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })));
});
Code explanation
var width = 960, height = 500
- This sets the width and height of the SVG element that will contain the map.var svg = d3.select("body").append("svg")
- This creates an SVG element and appends it to the body of the HTML page.var g = svg.append("g")
- This creates a group element in the SVG element.d3.json("https://d3js.org/us-10m.v1.json", function(error, us)
- This loads the TopoJSON data for the United States.g.append("g")
- This creates a new group element in the SVG element..selectAll("path")
- This selects all the path elements in the group..data(topojson.feature(us, us.objects.states).features)
- This binds the data to the path elements..enter().append("path")
- This adds a path element for each data element..attr("d", d3.geoPath())
- This sets the path's data attribute to the geographic path generator.
Here are some relevant links for further reading:
More of Javascript D3
- How do I create a timeline using d3.js?
- How do I create a zoomable line chart using d3.js?
- How do I use d3.js to zoom to a selected area?
- How do I create a zoomable chart using d3.js?
- How do I use the z-index property with d3.js?
- How do I set up the x axis in d3.js?
- How do I install and use D3.js with Yarn?
- How can I display Unix time using d3.js?
- How can I use d3.js to make an XMLHttpRequest?
- How can I use d3.js with Angular to create data visualizations?
See more codes...