You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用d3.js调用JSON API绘制GeoJSON地图显示空白如何解决?

代码问题及修复方案

    1. HTML语法错误
      你的d3引入部分多了一段未闭合的<script>标签:
    <script src="http://d3js.org/d3.v4.min.js"></script>
    <script <!-- 这一行是多余的,直接删掉 -->
    <script src="https://d3js.org/d3-geo-projection.v2.min.js"></script>
    

    这个错误会直接导致后续JS脚本无法正常解析运行,删掉多余的<script即可。

    1. 投影参数配置错误
      你当前的投影中心设置为[0, 0]、缩放值为1000,完全不在印度的地理范围,渲染出来的地图会落在SVG视口外,自然看不到内容。修改投影配置为适配印度的参数:
    const projection = d3.geoMercator()
      .translate([width / 2, height / 2])
      .center([78, 22]) // 调整到印度中心经纬度
      .scale(1400) // 调整缩放值到合适范围
      .precision(1);
    
    1. 错误处理顺序错误
      你当前先操作result.data再判断请求错误,若接口请求失败,result为undefined,直接访问属性会触发报错。调整错误处理顺序到函数最开头,同时额外加非空判断避免坐标解析报错:
    function getdata(error, result) {
      if (error) throw error; // 放到第一行先判断错误
      result.data.features.forEach((element, index) => {
        if (element.geometry && element.geometry.coordinates && element.geometry.coordinates !== "NA") {
          element.geometry.coordinates = JSON.parse(element.geometry.coordinates);
        }
      });
      // 剩余原有逻辑
    }
    
    1. 资源引入跨域风险
      你引入d3.v4.min.js用的是http协议,若你的页面运行在https环境下会被浏览器拦截,修改为https协议的引入地址:
    <script src="https://d3js.org/d3.v4.min.js"></script>
    
    1. 可选优化项
      给path增加默认描边,避免色块拼接时边界不清晰,同时修正无效的opacity赋值:
    svg.append("g")
      .selectAll("path")
      .data(result.data.features)
      .enter()
      .append("path")
      .style("fill", function(d) {
        return d.properties.color
      })
      .style("stroke", "#ccc") // 加默认描边
      .style("stroke-width", "0.5px")
      .attr("d", path)
      .on('mouseover', function(d, i) {
        d3.select(this).transition().duration(300).style("opacity", 0.8); // opacity取值范围0-1,不要设5
        // 剩余原有tooltip逻辑
      })
    

内容的提问来源于stack exchange,提问作者Mohammad Abass

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:06:00