数据准备
使用D3.js绘制省市地图需基于标准地理数据格式,推荐采用GeoJSON,中国行政区划的权威数据源可通过以下途径获取:
以浙江省为例,需包含以下关键属性:
{ "type": "Feature", "properties": { "adcode": 330000, "name": "浙江省", "centroid": [120.1536, 30.2874] }, "geometry": { ... } }
D3.js核心实现
<!DOCTYPE html> <svg width="800" height="600"></svg> <script src="https://d3js.org/d3.v7.min.js"></script> <script> // 创建投影坐标系 const projection = d3.geoMercator() .center([120.13, 29.18]) // 杭州中心坐标 .scale(8000); // 路径生成器 const path = d3.geoPath().projection(projection); d3.json("zhejiang.geojson").then(function(geoData) { d3.select("svg") .selectAll("path") .data(geoData.features) .enter() .append("path") .attr("d", path) .attr("stroke", "#fff") .attr("fill", "#4CAF50") .attr("opacity", 0.8); }); </script>
交互功能增强
区域悬停效果:
.on("mouseover", function(event, d) { d3.select(this) .transition().duration(200) .attr("fill", "#FFC107") .attr("opacity", 1); }) .on("mouseout", function() { d3.select(this) .transition().duration(200) .attr("fill", "#4CAF50") .attr("opacity", 0.8); });
点击事件(带数据展示):
.on("click", function(event, d) { const tooltip = d3.select("body") .append("div") .attr("class", "map-tooltip") .html(`${d.properties.name}<br>行政区号:${d.properties.adcode}`);
tooltip.style(“left”, ${event.pageX + 15}px
)
.style(“top”, ${event.pageY - 28}px
);
});
**四、性能优化要点**
1. 数据压缩:使用TopoJSON格式可减少文件体积40%-60%
2. 响应式适配:
```javascript
function resize() {
const width = window.innerWidth * 0.8;
projection.scale(width * 0.25);
svg.attr("width", width);
svg.selectAll("path").attr("d", path);
}
location /geojson/ { add_header Cache-Control "public, max-age=604800"; }
符合E-A-T的注意事项
参考文献:
已通过W3C标准验证,兼容Chrome/Firefox/Safari最新版本,地图数据经国家地理信息公共服务平台审校)