D3.js基于SVG、HTML和CSS,通过数据绑定实现图形动态更新,绘制地图需依赖以下关键步骤:
d3.json("https://cdn.jsdelivr.net/npm/us-atlas@3/states-10m.json").then(function(us) { const states = topojson.feature(us, us.objects.states); });
d3.geoAlbersUsa()
专为美国地图优化。 d3.geoPath()
将地理数据转换为SVG路径字符串。步骤1:初始化画布与比例尺
const width = 800, height = 500; const svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); const projection = d3.geoAlbersUsa().fitSize([width, height], states); const path = d3.geoPath().projection(projection);
步骤2:绘制州边界
svg.selectAll("path") .data(states.features) .enter().append("path") .attr("d", path) .attr("fill", "#e0e0e0") .attr("stroke", "#ffffff");
步骤3:添加交互效果
.on("mouseover", function(event, d) { d3.select(this).attr("fill", "#ff6b6b"); }) .on("mouseout", function() { d3.select(this).attr("fill", "#e0e0e0"); });
步骤4:标注主要城市
const cities = [{name: "纽约", coordinates: [-74.0060, 40.7128]}]; svg.selectAll("circle") .data(cities) .enter().append("circle") .attr("cx", d => projection(d.coordinates)[0]) .attr("cy", d => projection(d.coordinates)[1]) .attr("r", 4);
步骤5:响应式设计
window.addEventListener("resize", function() { const newWidth = window.innerWidth * 0.8; projection.fitSize([newWidth, height], states); svg.attr("width", newWidth) .selectAll("path").attr("d", path); });
颜色编码人口密度
通过d3.scaleQuantize()
将数据映射到颜色:
const colorScale = d3.scaleQuantize() .domain([0, 1000]) .range(["#f0f9e7","#bae4bc","#7bccc4","#43a2ca","#0868ac"]);
动态工具提示
使用d3-tip
库显示详细信息:
tip = d3.tip().attr("class", "d3-tip").html(d => `${d.properties.name}`); svg.call(tip);
数据权威性
us-atlas
保证数据准确性代码可信度
d3.geoAlbersUsa()
投影自动调整布局优化方向 | 技术方案 | 效果提升 |
---|---|---|
渲染优化 | 使用Canvas代替SVG | 减少DOM节点数 |
数据压缩 | 简化GeoJSON精度至1e-4 | 文件体积减少60% |
缓存策略 | 本地存储Map Tiles | 二次加载速度提升80% |
引用说明
地理数据来源:U.S. Census Bureau TIGER/Line
D3.js核心库:d3js.org
投影系统参考:Mike Bostock’s Albers USA