Search code examples
angulartypescriptmapsamchartsamcharts4

How do i bind & display rest api data to amchart4 geo maps using 'polygonTemplate.tooltipText' in Angular 9?


I'm trying to visualise covid19 data using amcharts4 geo map in Angular - similar to this demo

But prefer to only use hover to display data in map (timeline not necessary) - using 'polygonSeries.tooltipText' instead of the bubble. This is my api source Rest Api

All I get in the tooltip is the name, but no confirmed cases value. Screenshot geomaps

  • Generated service works fine
  • Getting rest api data is fine

This is what i use in geomaps.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;
    });
  }
}

When console logging getCasesData, my results return as follows:

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

further down the line:

[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}...

I appreciate anyone who can point me in the right direction. Thanks


Solution

  • Managed to resolve this: Issue was 'getCasesData()' function separately running outside 'ngAfterViewInit()'. Very silly mistake from my part

    Refactored code:

     // 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
      }
    

    If anyone has a better solution especially with parsing bigger sets of rest api data w/ Angular 8+, pls let me know. Thanks