【问题标题】:Highcharts / Highmaps with Angular - Cannot run demoHighcharts / Highmaps with Angular - 无法运行演示
【发布时间】:2019-01-13 05:03:38
【问题描述】:

我正在发现 Highcharts / Highmaps,现在,我想在我的机器上使用 Angular 6 重现一些演示示例,但我无法让它工作。

官方 JS 示例在这里:https://www.highcharts.com/maps/demo/map-drilldown(您可以点击“在 CodePen 中编辑”查看代码)

我试图像这样调整示例:

import { Component, OnInit } from '@angular/core';
import { Highcharts, MapChart } from 'angular-highcharts';

require('highcharts/modules/map')(Highcharts);

@Component({
  selector: 'app-demo-map-drilldown',
  templateUrl: './demo-map-drilldown.component.html',
  styleUrls: ['./demo-map-drilldown.component.css']
})
export class DemoMapDrilldownComponent implements OnInit {

  private chart: MapChart;

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    let data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']);
    let separators = Highcharts.geojson(Highcharts.maps['countries/us/us-all'], 'mapline');

    // Set drilldown pointers
    data.forEach((element, i) => {
      element.drilldown = element.properties['hc-key'];
      element.value = i; // Non-random bogus data
    });

    // Instantiate the map
    Highcharts.mapChart('container', {
      chart: {
        events: {
          drilldown: function (e) {
            if (!e.seriesOptions) {
              let chart = this;
              let mapKey = 'countries/us/' + e.point.drilldown + '-all';
              // Handle error, the timeout is cleared on success
              let fail = setTimeout(function () {
                if (!Highcharts.maps[mapKey]) {
                  chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
                  fail = setTimeout(function () {
                    chart.hideLoading();
                  }, 1000);
                }
              }, 3000);

              // Show the spinner
              chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner

              //data = Highcharts.geojson(Highcharts.maps[mapKey]);
              data = Highcharts.maps[mapKey];

              // Set a non-random bogus value
              data.forEach((element, i) => {
                element.value = i; // Non-random bogus data
              });

              // Hide loading and add series
              chart.hideLoading();
              clearTimeout(fail);
              chart.addSeriesAsDrilldown(e.point, {
                name: e.point.name,
                data: data,
                dataLabels: {
                  enabled: true,
                  format: '{point.name}'
                }
              });

            }

            this.setTitle(null, { text: e.point.name });
          },
          drillup: function () {
            this.setTitle(null, { text: '' });
          }
        }
      },

      title: {
        text: 'Highcharts Map Drilldown'
      },

      subtitle: {
        text: '',
        floating: true,
        align: 'right',
        y: 50,
        style: {
          fontSize: '16px'
        }
      },

      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
      },

      colorAxis: {
        min: 0,
        minColor: '#E6E7E8',
        maxColor: '#005645'
      },

      mapNavigation: {
        enabled: true,
        buttonOptions: {
          verticalAlign: 'bottom'
        }
      },

      plotOptions: {
        map: {
          states: {
            hover: {
              color: '#EEDD66'
            }
          }
        }
      },

      series: [{
        data: data,
        name: 'USA',
        dataLabels: {
          enabled: true,
          format: '{point.properties.postal-code}'
        }
        }, {
          type: 'mapline',
          data: separators,
          color: 'silver',
          enableMouseTracking: false,
          animation: {
            duration: 500
          }
      }],

      drilldown: {
        activeDataLabelStyle: {
          color: '#FFFFFF',
          textDecoration: 'none',
          textOutline: '1px #000000'
        },
        drillUpButton: {
          relativeTo: 'spacingBox',
          position: {
            x: 0,
            y: 60
          }
        }
      }
    });
  }
}

但到目前为止还没有运气。在这里,我收到错误geojson is undefined,我的编辑器(Visual Studio Code)强调了我对 Highcharts 的所有调用(.geojson.maps.mapChart)。

我的app.module.ts 文件如下所示:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ChartModule, HIGHCHARTS_MODULES } from 'angular-highcharts';
import * as more from 'highcharts/highcharts-more.src';
import * as exporting from 'highcharts/modules/exporting.src';
import * as highstock from 'highcharts/modules/stock.src';
import * as highmaps from 'highcharts/modules/map.src';
import * as drilldown from 'highcharts/modules/drilldown.src';
import * as data from 'highcharts/modules/data.src';
import * as exportdata from 'highcharts/modules/export-data.src';
import * as offline from 'highcharts/modules/offline-exporting.src';

import { AppComponent } from './app.component';
import { DemoMapDrilldownComponent } from './demo-map-drilldown/demo-map-drilldown.component';

@NgModule({
  declarations: [
    AppComponent,
    DemoMapDrilldownComponent,
  ],
  imports: [
    BrowserModule,
    ChartModule,
  ],
  providers: [
    {
      provide: HIGHCHARTS_MODULES,
      useFactory: () => [more, exporting, highstock, highmaps, drilldown, data, exportdata, offline]
    }, // add as factory to your providers
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

如您所见,我尝试从 Highcharts 中导入各种模块(基于几个教程),但没有任何改进...

我对 Highcharts 完全迷失了方向。显然,我的设置和/或我使用这个框架时出了点问题,但文档根本没有帮助,我找不到任何完整、详细的 Angular 教程。

至少有人可以帮我在 Angular 应用程序中运行这个官方示例吗?

更新:感谢@daniel_s,我现在使用官方包装器highcharts-angular 并摆脱了编辑器错误。 我在一个新项目的控制台中运行了npm install highcharts-angular --save 然后npm install highcharts --save

你可以在这里看到这个项目:https://codesandbox.io/s/38o5n9qor1 (我在沙箱中添加了 highcharts-angular、highcharts 和 highcharts-map 作为依赖项) 在控制台中,我们得到了错误:

ERROR TypeError: "a is undefined"
geojson             https://38o5n9qor1.codesandbox.io/node_modules/highcharts/highmaps.js:435:407
ngAfterViewInit     https://38o5n9qor1.codesandbox.io/src/app/official-example/official-example.component.ts:18:20

您能检查并帮助我更正我的代码吗?

【问题讨论】:

  • 您是否尝试过使用我们的官方 Highcharts Angular 包装器?这是 npm 包链接:npmjs.com/package/highcharts-angular。我怀疑你的实现有点错误,但我只是猜测。您能否尝试在 StackBlitz 或 CodeSandbox 等代码沙箱中准备您的应用程序示例?如果是,请提供给我。
  • @daniel_s 我觉得很傻。我一直在使用npmjs.com/package/angular-highcharts(这是我找到的第一个谷歌结果)而不是 highcharts-angular,但没有怀疑它不是官方包装器。使用 highcharts-angular,编辑器错误消失了!非常非常感谢你 !所以现在我的问题是将示例重写为 Angular 组件。请查看我的编辑。

标签: angular highcharts


【解决方案1】:

我知道这可能不是确切的答案,但如果有人有兴趣从 Highcharts official documentation 绘制 美国地图示例,您可能会遇到地图未渲染或很多控制台错误。


在这里,我想简要写几个步骤,以使该示例能够正常工作,以防万一您遇到同样的情况。

步骤:
1) 从here 下载(或使用CDN)US-ALLUS-CAPITALS

2) 完成后,将 JSON 文件放入您的项目数据文件夹(或您喜欢的任何其他位置)。

3) 在地图渲染之前,请确保您可以使用httpClient 获取 JSON 数据:

  this._httpClient.get('data/us-all.json').first().subscribe((map: any) => {
      this._httpClient.get('data/us-capitals.json').first().subscribe((json: any) => {
...

4) 现在使用下面的代码来渲染地图:

HTML

  <div [chart]="mapChart"
       style="min-width: 60vw; max-width: 100vw; height: 70vh; margin: 0 auto"></div>

Typescript/JS

...  

 public ngOnInit(): void {
    MapModule(Highcharts)

    this._httpClient.get('data/us-all.json').first().subscribe((map: any) => {
      this._httpClient.get('data/us-capitals.json').first().subscribe((json: any) => {
        const data: any[] = []
        forEach(USCapitals.default, (elm) => {
          elm.z = elm.population
          data.push(elm)
        })

        this.mapChart = new MapChart({
          title: {
            text: 'Highmaps lat/lon demo'
          },

          tooltip: {
            pointFormat: '{point.capital}, {point.parentState}<br>' +
              'Lat: {point.lat}<br>' +
              'Lon: {point.lon}<br>' +
              'Population: {point.population}'
          },
          xAxis: {
            crosshair: {
              zIndex: 5,
              dashStyle: 'dot',
              snap: false,
              color: 'gray'
            }
          },
          yAxis: {
            crosshair: {
              zIndex: 5,
              dashStyle: 'dot',
              snap: false,
              color: 'gray'
            }
          },
          mapNavigation: {
          enabled: true,
            buttonOptions: {
              alignTo: 'spacingBox'
            }
          },
          legend: {
            enabled: true
          },
          colorAxis: {
            min: 0
          },
          series: [
          {
             name: 'Basemap',
             mapData: USMap.default,
             borderColor: '#606060',
             nullColor: 'rgba(200, 200, 200, 0.2)',
             showInLegend: false
          } as Highcharts.SeriesMapOptions,
          {
             type: 'mapbubble',
             dataLabels: {
               enabled: true,
               format: '{point.capital}'
             },
             name: 'Enrolment by States',
             data: data,
             maxSize: '12%',
             color: Highcharts.getOptions().colors[ 0 ],
             point: {
               events: {
                  click: event => {
                    alert('you have clicked on map bubble.')
                  }
               }
             }
          },
          {
            name: 'Separators',
            type: 'mapline',
            data: Highcharts.geojson(USMap.default, 'mapline'),
            color: '#101010',
            enableMouseTracking: false,
            showInLegend: false
          }
         ]
        })
      })
    })
  }

以上内容足以查看带有州的基本美国地图。


更新

您也可以像 here 那样使用直接 JSON 导入。

【讨论】:

  • USCapitals.default、USMap.default 到底是什么?您能否请一个关于 stackblitz 的演示,以对其他人也有帮助。
【解决方案2】:

它不起作用,因为您根本没有在项目中导入任何地图。不幸的是,没有包含所有地图的npm 包,但是您可以手动创建一个包含您需要的地图的文件,并将文件直接导入您的项目。以下是如何将地图添加到您的项目的示例:https://codesandbox.io/s/vm58jk5005

最好的问候!

【讨论】:

  • 非常感谢您的帮助!!这个演示很棒,正是我一直在拼命寻找的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2015-10-24
相关资源
最近更新 更多