Как привязать и отобразить остальные данные API для географических карт amchart4, используя 'polygonTemplate.tooltipText' в Angular 9? - PullRequest
0 голосов
/ 25 марта 2020

Я пытаюсь визуализировать данные covid19, используя географическую карту amcharts4 в Angular - аналогично demo

Но предпочитаю использовать hover только для отображения данных на карте (временная шкала не необходимо) - используя 'polygonSeries.tooltipText' вместо пузыря. Это мой источник API Rest Api

Все, что я получаю во всплывающей подсказке, это имя, но не подтвержденное значение случаев. Снимок экрана geomaps

  • Сгенерированный сервис работает нормально
  • Получение данных API остальных в порядке

Это то, что я использую в геомапах. component.ts

import { Component, OnInit, NgZone, AfterViewInit } from '@angular/core';
import * as am4core from '@amcharts/amcharts4/core';
import * as am4maps from "@amcharts/amcharts4/maps";
import am4geodata_worldLow from '@amcharts/amcharts4-geodata/worldLow';
import am4themes_animated from '@amcharts/amcharts4/themes/animated';
import { MapServiceService } from '../service/map-service.service';
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end

@Component({
  selector: 'app-geomaps',
  templateUrl: './geomaps.component.html',
  styleUrls: ['./geomaps.component.css']
})

export class GeomapsComponent implements OnInit, AfterViewInit {
  public caseData = [];

  private mapChart: am4maps.MapChart;

  constructor(private zone: NgZone, private mapsService: MapServiceService) { }

  // Inject NgZone service and add ngAfterViewInit method which will create our chart
  ngAfterViewInit() {
    this.zone.runOutsideAngular(() => {

      // Declare our chart to display to html id='chartdiv' map instance
      let mapChart = am4core.create("chartdiv", am4maps.MapChart);

      // Low-detail map - set map definition
      mapChart.geodata = am4geodata_worldLow;

      // set projection
      mapChart.projection = new am4maps.projections.Miller();

      //  polygon represented by objects map areas (defines how country look and behave)
      let polygonSeries = mapChart.series.push(new am4maps.MapPolygonSeries());
      polygonSeries.data = this.caseData; // Our case data
      polygonSeries.useGeodata = true;

      // Bind our properties to data
      // polygonSeries.data = 
      // [{
      //   "id": "US",
      //   "name": "United States",
      //   "value": 100,
      //   "fill": am4core.color("#F05C5C")
      // }, {
      //   "id": "FR",
      //   "name": "France",
      //   "value": 50,
      //   "fill": am4core.color("#5C5CFF")
      // }];

      // configure series
      let polygonTemplate = polygonSeries.mapPolygons.template;
      polygonTemplate.tooltipText = "{name}: {value}"; // TooltipText
      polygonTemplate.fill = am4core.color("#74B266");

      // Create hover state and set alternative fill color
      let hs = polygonTemplate.states.create("hover");
      hs.properties.fill = am4core.color("#003399");

      // Exclude antartica iso-2="AQ"
      polygonSeries.exclude = ["AQ"];

      mapChart.smallMap = new am4maps.SmallMap();
      mapChart.smallMap.series.push(polygonSeries);

    });
  }

  ngOnDestroy() {
    this.zone.runOutsideAngular(() => {
      if (this.mapChart) {
        this.mapChart.dispose();
      }
    });
  }

  ngOnInit() {
    this.getCasesData();
  }

  getCasesData() {
    this.mapsService.getAll().subscribe(data => {
      for (const d of (data as any)) {
        this.caseData.push({
          id: d.iso2,
          name: d.countryRegion,
          provinceState: d.provinceState,
          value: d.confirmed
        });
      }
      console.log(this.caseData);
      // return this.caseData;
    });
  }
}

Когда консоль регистрирует getCasesData, мои результаты возвращаются следующим образом:

[0 … 99]
    0: {multiPolygon: Array(1), id: "TV", madeFromGeoData: true, name: "Tuvalu"}
    1: {multiPolygon: Array(1), id: "BV", madeFromGeoData: true, name: "Bouvet Island"}...

дальше по линии:

[300 … 399]
    300: {id: "SA", name: "Saudi Arabia", provinceState: null, value: 900}
    301: {id: "FI", name: "Finland", provinceState: null, value: 880}
    302: {id: "US", name: "US", provinceState: "Michigan", value: 876}...

Я ценю любого, кто может указать мне в правильном направлении. Спасибо

1 Ответ

0 голосов
/ 31 марта 2020

удалось решить эту проблему: проблема заключалась в том, что функция 'getCasesData ()' работала отдельно от функции 'ngAfterViewInit ()'. Очень глупая ошибка с моей стороны

Измененный код:

 // Inject NgZone service and add ngAfterViewInit method which will create our chart
  ngAfterViewInit() {
  }

 // Insert function here
  getCasesData() {
    this.mapsService.getAll().subscribe(data => {
    this.tempData = data;
    this.tempData.forEach(values => {
      this.caseData.push({
        id: values.iso2,
        name: values.countryRegion,
        longitude: values.long,
        latitude: values.lat,
        value: values.confirmed
      });
    });
    console.log(this.caseData);

    // Running inside our function to get Data, otherwise it will return 'undefined'
    this._zone.runOutsideAngular(() => {

      // Declare our chart to display to html id='chartdiv' map instance
      let mapChart = am4core.create("chartdiv", am4maps.MapChart);

      // Low-detail map - set map definition
      mapChart.geodata = am4geodata_worldLow;

      // set projection
      mapChart.projection = new am4maps.projections.Miller();

      //  polygon represented by objects map areas (defines how country look and behave)
      let polygonSeries = mapChart.series.push(new am4maps.MapPolygonSeries());

      // polygonSeries.data = this.caseData;  
      polygonSeries.useGeodata = true;

      // Bind our properties to data
      polygonSeries.data = this.caseData;

      // configure series
      let polygonTemplate = polygonSeries.mapPolygons.template;

      polygonTemplate.tooltipText = "{name} confirmed cases: {value}";
      polygonTemplate.fill = am4core.color("#74B266");
      polygonTemplate.propertyFields.fill = "fill";

      // Create hover state and set alternative fill color
      let hs = polygonTemplate.states.create("hover");
      hs.properties.fill = am4core.color("#003399");

      // Exclude antartica iso-2="AQ"
      polygonSeries.exclude = ["AQ"];
      polygonSeries.calculateVisualCenter = true;

    });

  });
  }

  ngOnDestroy() {
    this._zone.runOutsideAngular(() => {
      if (this.mapChart) {
        this.mapChart.dispose();
      }
    });
  }

  ngOnInit() {
    this.getCasesData(); // On initialise
  }

Если у кого-то есть лучшее решение, особенно с анализом больших наборов данных API отдыха с / 1007 * 8+, пожалуйста, позвольте мне знать. Спасибо

...