错误:在Angular的gvjs_dp GeoChart中未定义容器

时间:2018-12-17 14:26:51

标签: angular charts google-visualization

这是我的HTML代码:

<div id="geochart" #geochart> </div>

这是我的TS代码:

ngOnInit() {
  google.charts.load('current', {'packages':['corechart','geochart'], mapsApiKey: 'XXXXmyAPIKEYXXXX'});

this.http.post(url,data,{responseType: 'text'})
 .subscribe(
    data => {
      this.geoChartArray = JSON.parse(data).data;
      this.drawGeoChart();
    },
    error => {
      console.log(error);
    });
}


drawGeoChart() {
   var geo_1_options = { is3D: true };   
   var geo_1_data = google.visualization.arrayToDataTable(this.geoChartArray);
   var domElement = document.getElementById('geochart');
   var geo_1_chart = new google.visualization.GeoChart(domElement);
   geo_1_chart.draw(geo_1_data, geo_1_options);
}

有时会加载GeoChart,有时会出现此错误。我无法弄清楚到底是什么引起了错误。

3 个答案:

答案 0 :(得分:1)

您是否尝试将代码移至ngAfterViewInit?而且也不直接使用DOM API:

@ViewChild('geochart') geochartEl: ElementRef;
ngAfterViewInit() {
  this.http...subscribe(() => {

  })
}

draw(...)  {
  const domElement = this.geochartEl.nativeElement;
  ...
}

答案 1 :(得分:-1)

我认为您需要根据文档(https://developers.google.com/chart/interactive/docs/gallery/geochart)中提供的小提琴来设置google.charts.setOnLoadCallback();

尝试这样:

google.charts.load('current', {
  'packages': ['geochart'],
  'mapsApiKey': 'XXXXmyAPIKEYXXXX'
});

google.charts.setOnLoadCallback(drawGeoChart);

this.http.post(url,data,{responseType: 'text'})
 .subscribe(
    data => {
      this.geoChartArray = JSON.parse(data).data;
      this.drawGeoChart();
    },
    error => {
      console.log(error);
    });
}

drawGeoChart() {
  var data = google.visualization.arrayToDataTable([
      ['Country', 'Popularity'],
      ['Germany', 200],
      ['United States', 300],
      ['Brazil', 400],
      ['Canada', 500],
      ['France', 600],
      ['RU', 700]
    ]);

  var options = {};

  var chart = new google.visualization.GeoChart(document.getElementById('geochart'));

  chart.draw(data, options);
}

答案 2 :(得分:-1)

在绘制图表之前,需要等待页面和Google图表加载。
谷歌的加载语句将默认等待页面加载。

您可以在load语句中设置“加载时” callback
然后获取数据,
并绘制图表。

请参阅以下代码段...

ngOnInit()
{
  google.charts.load('current', {
    packages: ['corechart','geochart'],
    mapsApiKey: 'XXXXmyAPIKEYXXXX',
    callback: this.getData
  });
}

getData()
{
  this.http.post(url,data,{responseType: 'text'})
    .subscribe(
      data =>
        {
          this.geoChartArray = JSON.parse(data).data;
          this.drawGeoChart();

        },
      error =>
        {
          console.log(error);
        }
    );
}

drawGeoChart()
{
  var geo_1_options = { is3D: true };
  var geo_1_data = google.visualization.arrayToDataTable(this.geoChartArray);
  var domElement = document.getElementById('geochart');
  var geo_1_chart = new google.visualization.GeoChart(domElement);
  geo_1_chart.draw(geo_1_data, geo_1_options);
}