|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | + <head> |
| 4 | + <meta charset="utf-8" /> |
| 5 | + <meta http-equiv="X-UA-Compatible" content="IE=edge" /> |
| 6 | + <title>US Choropleth Map</title> |
| 7 | + <meta name="description" content="force directed graph example" /> |
| 8 | + <meta name="viewport" content="width=device-width, initial-scale=1" /> |
| 9 | + <script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script> |
| 10 | + <script src="../web_modules/d3/dist/d3.js"></script> |
| 11 | + <script src="https://cdn.jsdelivr.net/npm/topojson-client"></script> |
| 12 | + <link href="./style.css" rel="stylesheet" /> |
| 13 | + <style> |
| 14 | + path { |
| 15 | + stroke: #999; |
| 16 | + } |
| 17 | + path:hover { |
| 18 | + stroke: black; |
| 19 | + } |
| 20 | + </style> |
| 21 | + </head> |
| 22 | + |
| 23 | + <body> |
| 24 | + <h1>US Choropleth Map</h1> |
| 25 | + |
| 26 | + <script> |
| 27 | + const margin = { |
| 28 | + top: 10, |
| 29 | + bottom: 10, |
| 30 | + left: 10, |
| 31 | + right: 10, |
| 32 | + }; |
| 33 | + const width = 800 - margin.left - margin.right; |
| 34 | + const height = 600 - margin.top - margin.bottom; |
| 35 | + |
| 36 | + // Creates sources <svg> element and inner g (for margins) |
| 37 | + const svg = d3 |
| 38 | + .select("body") |
| 39 | + .append("svg") |
| 40 | + .attr("width", width + margin.left + margin.right) |
| 41 | + .attr("height", height + margin.top + margin.bottom) |
| 42 | + .append("g") |
| 43 | + .attr("transform", `translate(${margin.left}, ${margin.top})`); |
| 44 | + |
| 45 | + ///////////////////////// |
| 46 | + const projection = d3.geoAlbersUsa(); |
| 47 | + const path = d3.geoPath(projection); |
| 48 | + const color = d3.scaleSequential(d3.interpolateBlues); |
| 49 | + |
| 50 | + d3.json('https://cdn.jsdelivr.net/npm/us-atlas/states-10m.json').then((us) => { |
| 51 | + const states = topojson.feature(us, us.objects.states).features; |
| 52 | + const nation = topojson.feature(us, us.objects.nation).features[0]; |
| 53 | + |
| 54 | + // scale to fit bounds |
| 55 | + projection.fitSize([width, height], nation); |
| 56 | + |
| 57 | + const data = states.map((feature) => ({ |
| 58 | + feature: feature, |
| 59 | + name: feature.properties.name, |
| 60 | + value: Math.random() // random value |
| 61 | + })); |
| 62 | + |
| 63 | + const paths = svg.selectAll('path').data(data) |
| 64 | + .join((enter) => { |
| 65 | + const p = enter.append('path'); |
| 66 | + p.on('mouseenter', function() { |
| 67 | + // move the SVG element after all other elements to be on the top |
| 68 | + d3.select(this).raise(); |
| 69 | + }); |
| 70 | + p.append('title'); |
| 71 | + return p; |
| 72 | + }) |
| 73 | + .attr('d', (d) => path(d.feature)) |
| 74 | + .style('fill', (d) => color(d.value)); |
| 75 | + paths.select('title').text((d) => d.name); |
| 76 | + }); |
| 77 | + </script> |
| 78 | + </body> |
| 79 | +</html> |
0 commit comments