如何用 D3.js 绘制地图

如何用 D3.js 绘制地图
最新回答
青澜饮舟

2026-07-25 22:49:21

使用 D3.js 绘制地图主要涉及数据准备和代码实现两个核心步骤。以下是详细指南:

一、数据准备
  1. 获取 GeoJSON 数据

    GeoJSON 是存储地理信息的标准格式,包含点、线、多边形等要素。

    推荐数据源:

    阿里云地图选择器:提供中国各省市 GeoJSON 数据(示例截图如下)。

    Natural Earth:提供全球国家/地区数据。

    GitHub 开源项目:如 topojson 格式的全球数据。

  2. 数据格式示例

    { "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "北京市" }, "geometry": { "type": "Polygon", "coordinates": [[[116.4, 39.9], ...]] } } ]}
二、代码实现步骤1. 基础 HTML 结构<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>D3.js 地图</title> <script src="
https://d3js.org/d3.v7.min.js"></script></head><body>
<div id="map-container"></div> <script src="map.js"></script></body></html>2. JavaScript 核心逻辑(map.js)// 1. 设置画布和投影const width = 1000, height = 800;const svg = d3.select("#map-container") .append("svg") .attr("width", width) .attr("height", height);// 使用墨卡托投影(可根据需求调整中心点和缩放比例)const projection = d3.geoMercator() .center([104.0, 37.5]) // 中国中心点经纬度 .scale(800) .translate([width / 2, height / 2]);const path = d3.geoPath().projection(projection);// 2. 加载并绘制地图d3.json("china.geojson").then(data => { svg.selectAll("path") .data(data.features) .enter() .append("path") .attr("d", path) .attr("fill", "#69b3a2") // 填充颜色 .attr("stroke", "#fff") // 边界颜色 .attr("stroke-width", 1);});三、关键点说明
  1. 投影类型

    d3.geoMercator():常用投影,适合全球或大范围地图。

    其他投影:geoAlbers(美国常用)、geoOrthographic(球形投影)等。

  2. 交互扩展

    鼠标悬停效果:

    .on("mouseover", (event, d) => { d3.select(event.currentTarget).attr("fill", "orange");}).on("mouseout", (event, d) => { d3.select(event.currentTarget).attr("fill", "#69b3a2");});

    点击事件:

    .on("click", (event, d) => console.log(d.properties.name));
  3. 性能优化

    对于复杂地图(如全球数据),使用 TopoJSON 格式(比 GeoJSON 更轻量)。

    通过 d3.tile() 实现瓦片地图(需结合 OpenStreetMap 等服务)。

四、完整示例效果

五、常见问题解决
  1. 地图显示空白

    检查 GeoJSON 数据路径是否正确。

    确认投影中心点(center)和缩放比例(scale)是否适合目标区域。

  2. 跨域问题

    本地开发时,使用 http-server 或 live-server 启动本地服务器,避免直接文件访问。

  3. 自定义样式

    通过 CSS 或直接设置 SVG 属性调整颜色、透明度等:

    .attr("fill", d => d.properties.population > 1000000 ? "red" : "blue")

通过以上步骤,你可以快速实现一个基础的 D3.js 地图,并根据需求扩展交互功能或优化性能。