{ "type": "FeatureCollection", "features": [{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [[/* 坐标数组 */]] } }] }
<script src="https://d3js.org/d3.v7.min.js"></script> <script src="https://unpkg.com/topojson-client@3"></script>
const width = 800; const height = 600;
const svg = d3.select(“#map-container”)
.append(“svg”)
.attr(“width”, width)
.attr(“height”, height);
2. **配置地理投影
```javascript
const projection = d3.geoMercator()
.center([116.4, 39.9]) // 北京市中心坐标
.scale(1200)
.translate([width/2, height/2]);
**路径生成器
const path = d3.geoPath() .projection(projection);
**数据加载与转换
d3.json("china.topojson").then(function(topology){ const geojson = topojson.feature( topology, topology.objects.provinces );
svg.selectAll(“path”)
.data(geojson.features)
.enter()
.append(“path”)
.attr(“d”, path)
.style(“fill”, “#67b7dc”)
.style(“stroke”, “#fff”);
});
5. **交互增强实现
```javascript
.on("mouseover", function(event, d){
d3.select(this)
.transition()
.duration(200)
.style("fill", "#ff7f0e");
})
.on("mouseout", function(d){
d3.select(this)
.transition()
.duration(200)
.style("fill", "#67b7dc");
});
**性能优化策略
transform
替代直接DOM操作数据源选择
投影选择原则
**移动端适配方案
function responsiveSVG() { const container = d3.select("#map-container"); const newWidth = container.node().getBoundingClientRect().width;
svg.attr(“width”, newWidth);
projection.scale(newWidth * 0.4);
svg.selectAll(“path”).attr(“d”, path);
}
window.addEventListener(“resize”, responsiveSVG);
---
### 四、常见问题诊断
| 问题现象 | 解决方案 |
|---------|----------|
| 地图元素偏移 | 检查投影中心点设置 |
| 点击事件失效 | 验证数据绑定顺序 |
| 渲染性能低下 | 启用GPU加速渲染 |
| 边界锯齿明显 | 应用抗锯齿SVG滤镜 |
---
### 五、进阶开发方向
1. 三维扩展:集成Three.js实现立体地形
2. 时序动画:结合D3-transition实现历史演变
3. 热力图层:通过WebGL加速渲染百万级数据点
4. 拓扑分析:实现路径规划等空间运算功能
```javascript
// 实时数据更新示例
function updateData(newDataset) {
svg.selectAll("path")
.data(newDataset)
.transition()
.duration(1000)
.style("fill", d => colorScale(d.value));
}
可信数据源参考: