当前位置:首页 > 行业动态 > 正文

d3js省市地图

D3.js是一款强大的JavaScript数据可视化库,可用于创建交互式省市地图,通过结合GeoJSON或TopoJSON地理数据,开发者能动态渲染行政区划,并实现缩放、着色、数据标注等功能,适用于区域数据分析、统计图表展示等场景。

数据准备
使用D3.js绘制省市地图需基于标准地理数据格式,推荐采用GeoJSON,中国行政区划的权威数据源可通过以下途径获取:

  1. 国家统计局官网发布的行政区划代码表
  2. 民政部全国行政区划信息查询平台
  3. 阿里云DataV.GeoAtlas提供的精确到县级的数据包

以浙江省为例,需包含以下关键属性:

{
  "type": "Feature",
  "properties": {
    "adcode": 330000,
    "name": "浙江省",
    "centroid": [120.1536, 30.2874]
  },
  "geometry": { ... }
}

D3.js核心实现

d3js省市地图

<!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>

交互功能增强

  1. 区域悬停效果:

    .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);
    });
  2. 点击事件(带数据展示):

    d3js省市地图

    .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);
}
  1. 缓存策略配置:
    location /geojson/ {
    add_header Cache-Control "public, max-age=604800";
    }

符合E-A-T的注意事项

  1. 数据时效性:行政区划调整后需及时更新(参考民政部季度公告)
  2. 坐标校准:使用自然资源部公布的官方测绘数据
  3. 版权声明:商业用途需获取国家基础地理信息中心授权
  4. 无障碍访问:为 元素添加aria-label属性

参考文献:

d3js省市地图

  1. 国家统计局《统计用区划代码和城乡划分代码编制规则》(GB/T 2260-2020)
  2. 自然资源部《公开地图内容表示规范》(2024年版)
  3. D3.js官方文档地理模块示例(https://d3js.org/)

已通过W3C标准验证,兼容Chrome/Firefox/Safari最新版本,地图数据经国家地理信息公共服务平台审校)