网站搜索

typescript - 在 Angular 中出现错误:d3.geoAlbersUsa 不是一个函数


我正在尝试在一个 Angular 5 项目中创建一个美国各州的 d3 地图,参考以下示例:

http://bl.ocks.org/mbostock/4699541

所以当我在 .ts 文件中编写代码并编译时,它会给我一个错误,提示:'d3.geoAlbersUsa 不是一个函数'。

以下是代码:

import { Component } from '@angular/core';
import * as d3TimeFormat from 'd3-time-format';
import * as d3 from 'd3-selection';
import * as d3Scale from 'd3-scale';
import * as d3Shape from 'd3-shape';
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';
import * as topo from 'topojson';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor() {}

  ngOnInit() {
    this.callMap();
  } 

  callMap() {
    var width = 960,
    height = 500,
    active = d3.select(null);

    var projection = d3.geoAlbersUsa()
        .scale(1000)
        .translate([width / 2, height / 2]);

    var path = d3.geoPath()
        .projection(projection);

    var svg = d3.select("body").append("svg")
        .attr("width", width)
        .attr("height", height);

    svg.append("rect")
        .attr("class", "background")
        .attr("width", width)
        .attr("height", height)
        .on("click", reset);

    var g = svg.append("g")
        .style("stroke-width", "1.5px");

    d3.json("/mbostock/raw/4090846/us.json", function(error, us) {
      if (error) throw error;

      g.selectAll("path")
          .data(topo.feature(us, us.objects.states).features)
        .enter().append("path")
          .attr("d", path)
          .attr("class", "feature")
          .on("click", clicked);

      g.append("path")
          .datum(topo.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
          .attr("class", "mesh")
          .attr("d", path);
    });
    ....
    ....

我在 index.html 中包含以下脚本:

  <script src="https://d3js.org/d3.v3.min.js"></script>
  <script src="https://d3js.org/topojson.v1.min.js"></script>
  <script src="https://d3js.org/d3-array.v1.min.js"></script>
  <script src="https://d3js.org/d3-geo.v1.min.js"></script>
  <script src="https://d3js.org/d3-selection.v1.min.js"></script>
  <script src="https://d3js.org/d3-collection.v1.min.js"></script>
  <script src="https://d3js.org/d3-dispatch.v1.min.js"></script>
  <script src="https://d3js.org/d3-request.v1.min.js"></script>

请在这件事上帮我。

谢谢。

答案#1

应该是 d3.geo.albersUsa() 并且 geoPath 应该是 d3.geo.path()

答案#2

如果有人仍然需要解决这个问题:

你需要导入

import geoAlbersUsa from 'd3-geo';

并像这样使用它:

var projection = geoAlbersUsa()
        .scale(1000)
        .translate([width / 2, height / 2]);