D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
Andrew-Reid
Full window
Github gist
Map Data Sources - Alternating CSVs - Load on Demand
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> .land { fill: #a1d99b; } svg { background: #deebf7; } .boundary { fill:none; stroke: white; } </style> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="https://d3js.org/topojson.v1.min.js"></script> </head> <body> <div id="map"></div> <input class="selector" type="button" value="Customers" id="customers.csv"/> <input class="selector" type="button" value="Employees" id="employees.csv"/> <script> var width = 960; var height = 480; var svg = d3.select("#map") .append("svg") .attr("width",width) .attr("height",height); var projection = d3.geoMercator() .center([0,5]) .scale(200) .rotate([-180,0]); var path = d3.geoPath().projection(projection); var g1 = svg.append('g'); var g2 = svg.append('g'); // Append the world: d3.json("world.json", function (error, world) { g1.insert("path", ".land") .datum(topojson.feature(world, world.objects.land)) .attr("class", "land") .attr("d", path); g1.insert("path", ".boundary") .datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; })) .attr("class", "boundary") .attr("d", path); }); // append intial data d3.csv('customers.csv', function(error,data) { g2.selectAll('circle') .data(data) .enter() .append('circle') .attr('cx',function(d) {return projection([d.long,d.lat])[0]; }) .attr('cy',function(d) {return projection([d.long,d.lat])[1]; }) .attr('r',4) .attr('stroke','steelblue') .attr('fill','white'); }); d3.selectAll('.selector') .on('click', function(d) { update(this.id); }) // update function: function update(source) { d3.csv(source, function(error,data) { var circles = g2.selectAll('circle') .data(data) // append new circles and remove excess circles circles.enter() .append('circle') .attr('cx',function(d) {return projection([d.long,d.lat])[0]; }) .attr('cy',function(d) {return projection([d.long,d.lat])[1]; }) .transition() .attr('r',4) .attr('stroke',function() { if (source == "employees.csv") { return "red"; } else { return "steelblue" } }) .attr('fill','white') .duration(2000); circles.exit().transition().attr('r',0).duration(1000).remove(); // move circles circles.transition() .attr('cx',function(d) {return projection([d.long,d.lat])[0]; }) .attr('cy',function(d) {return projection([d.long,d.lat])[1]; }) .attr('r',4) .attr('stroke',function() { if (source == "employees.csv") { return "red"; } else { return "steelblue" } }) .duration(2000); }); } </script> </body> </html>
https://d3js.org/d3.v4.min.js
https://d3js.org/topojson.v1.min.js