D3.js(Data-Driven Documents)是一个基于JavaScript的数据可视化库,通过操作SVG、Canvas或HTML元素实现交互式图表,绘制地图的核心在于地理数据格式和地理投影:
d3.geoMercator
(墨卡托投影,适合Web地图)、d3.geoEquirectangular
(等距矩形投影)等。 从权威地理数据源(如Natural Earth)下载GeoJSON文件,或使用工具(如mapshaper)简化数据。
<!DOCTYPE html> <html> <head> <script src="https://d3js.org/d3.v7.min.js"></script> <style> .country { fill: #e0e0e0; stroke: #fff; stroke-width: 0.5px; } .country:hover { fill: #4CAF50; } </style> </head> <body> <div id="map-container"></div> <script> // 步骤2:加载数据并绘制 const width = 800, height = 600; const svg = d3.select("#map-container") .append("svg") .attr("width", width) .attr("height", height); d3.json("https://example.com/world.geojson").then(data => { // 步骤3:定义投影 const projection = d3.geoMercator() .fitSize([width, height], data); // 步骤4:生成路径生成器 const path = d3.geoPath().projection(projection); // 步骤5:绘制地图路径 svg.selectAll("path") .data(data.features) .enter() .append("path") .attr("class", "country") .attr("d", path) .on("mouseover", function() { d3.select(this).style("opacity", 0.7); }) .on("mouseout", function() { d3.select(this).style("opacity", 1); }); }); </script> </body> </html>
// 启用缩放 const zoom = d3.zoom() .scaleExtent([1, 8]) .on("zoom", (event) => { svg.attr("transform", event.transform); }); svg.call(zoom);
simplify
工具降低数据复杂度。 requestAnimationFrame
避免过度渲染。 .center([经度, 纬度])
)或缩放系数(.scale()
)。 d3.event.stopPropagation()
阻止事件冒泡。