【问题标题】:d3js enter is not a function issued3js enter 不是函数问题
【发布时间】:2021-01-16 17:14:08
【问题描述】:

我是 d3js 库的新手。我尝试绘制非洲大陆的轮廓,我有以下代码:

<!DOCTYPE html>
<meta charset="utf-8">
<head>
  <title>geoPath measures</title>
</head>

<body>
<svg id="my_dataviz" width="400" height="300"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>

<script>
  var svg = d3.select('#my_dataviz');
  var projection = d3.geoMercator().center([0, 5]);
  var geoGenerator = d3.geoPath().projection(projection);

  function update(geojson) {
    svg.append("g")
      .selectAll("path")
      .data(geojson.features)
      .enter()
        .append("path")
        .attr('d', geoGenerator);
  }

  d3.json('africa.json', function(err, json) {
    update(json)
  })
</script>
</body>
</html>

但是,我收到以下错误:

Uncaught TypeError: svg.append(...).selectAll(...).data(...).enter is not a function

有什么问题?我做错了什么?

【问题讨论】:

  • 最可能的错误原因可能是 geojson.features 不是数组。您可以记录并确认它是吗?
  • 是的,安德鲁,这是个问题。谢谢!

标签: javascript html d3.js


【解决方案1】:

您的map datatopoJson,但您将其视为geoJson。所以正如@AndrewReid 指出的那样,其中没有.features 属性。

您可以使用topoJson.js进行转换:

<html>
  <meta charset="utf-8" />
  <head>
    <title>geoPath measures</title>
  </head>

  <body>
    <svg id="my_dataviz" width="1000" height="1000"></svg>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
    <script src="//d3js.org/topojson.v1.min.js"></script>

    <script>
      var svg = d3.select('#my_dataviz');
      var projection = d3.geoMercator().center([0, 5]);
      var geoGenerator = d3.geoPath().projection(projection);

      function update(someTopoJson) {
      
        let geojson = topojson.feature(
          someTopoJson,
          someTopoJson.objects.continent_Africa_subunits
        );

        svg
          .append('g')
          .selectAll('path')
          .data(geojson.features)
          .enter()
          .append('path')
          .attr('d', geoGenerator)
          .attr('fill', 'steelblue');
      }

      d3.json(
        'https://raw.githubusercontent.com/deldersveld/topojson/master/continents/africa.json',
        function (err, json) {
          update(json);
        }
      );
    </script>
  </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2018-11-10
    • 2019-09-04
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多