Exploring dynamic data with Highcharts geomaps

API is being called to display data in the chartOptions. However, I am encountering an issue trying to pass it through this.letsTry. I am unsure where I am making a mistake.

[data-local.component.html]

<highcharts-chart id="container" [Highcharts]="Highcharts" [constructorType]="chartConstructor" [options]="chartOptions" style="width: 100%; height: 550px; display: block;">
</highcharts-chart> 

[data-local.component.ts file]

import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { DatalocalService } from 'src/app/services/datalocal.service';
import Highcharts from 'highcharts/highmaps';
import MapModule from 'highcharts/modules/map';
declare var require: any
const mapWorld = require('@highcharts/map-collection/custom/world.geo.json')
MapModule(Highcharts);
@Component({
  selector: 'app-data-local',
  templateUrl: './data-local.component.html',
  styleUrls: ['./data-local.component.scss']
})
export class DataLocalComponent implements OnInit {

  skipCountryVal: boolean = false;
  letsTry = [];
  constructor(
    private commonService: CommonService,
    private local: DatalocalService
  ) { }
 
  ngOnInit(): void {
    let args1 = {
      'body': `query {
        DataLocal(skip: ${this.skipCountryVal ? 1 : 0}, first: 10) {
          Count
          Code
        }
      }
    `
    };
    this.DataLocal(args1);
  }

  Highcharts: typeof Highcharts = Highcharts;
  chartConstructor = "mapChart";
  chartData = [{ code3: "ABW", z: 105 }, { code3: "AFG", z: 35530 }];

  chartOptions: Highcharts.Options = {
    chart: {
      map: mapWorld
    },
    title: {
      text: "Data local report"
    },
    subtitle: { 
      text:
        // 'Source map: <a href="http://code.highcharts.com/mapdata/custom/world.js">World, Miller projection, medium resolution</a>'
        ''
    },
    mapNavigation: {
      enabled: true,
      buttonOptions: {
        alignTo: "spacingBox"
      }
    },
    legend: {
      enabled: true
    },
    colorAxis: {
      min: 0
    },
    series: [
      {
        type: "map",
        name: "Random data",
        states: {
          hover: {
            color: "#24e9ad"
          }
        },
        dataLabels: {
          enabled: true,
          format: "{point.name}"
        },
        allAreas: true,
        data: this.letsTry
      }
    ]
  };

  // data localization api
  DataLocal(args1) {
    this.localService.DataLocal(args1).subscribe(
      (data) => {
        let tempGeoData = [];
        let apiGeoData = data['data']['DataLocal'];
        for (let i = 0; i < apiGeoData.length; i++) {
          tempGeoData.push(
            [
              data['data']['DataLocal'][i]['Code'],
              data['data']['DataLocal'][i]['Count']
            ]
            
          )
          // this.chartOptions.data[i] = tempGeoData[i];
          this.letsTry = tempGeoData;
        }
        console.log('Data from API', this.letsTry);
      }
    )
  }
}

[sample data from API]

{
  "data": {
    "DataLocal": [
      {
        "CodeCount": 1998,
        "Code": "au"
      },
      {
        "CodeCount": 7422,
        "Code": "fr"
      },
      {
        "CodeCount": 3062,
        "Code": "in"
      },
    ]
  }
}

Answer №1

There seem to be a couple of issues with your current code implementation:

  1. Initializing HighCharts after letsTry has data
  2. Assigning letsTry inside the for loop instead of outside

Make sure to initialize chartoption only after DataLocal completes and letsTry is updated with values.

// Implementation of data localization api
DataLocal(args1) {
  return this.localService.DataLocal(args1).subscribe( // Make sure to return this promise in order to use it with .then()
    (data) => {
      let tempGeoData = [];
      let apiGeoData = data['data']['DataLocal'];
      for (let i = 0; i < apiGeoData.length; i++) {
        tempGeoData.push(
          [
            data['data']['DataLocal'][i]['Code'],
            data['data']['DataLocal'][i]['Count']
          ]
        );
      }

      this.letsTry = tempGeoData; // Ensure that this line is placed outside the loop

      console.log('Received data from API', this.letsTry);

      return "success";
    }
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Highcharts plots only appear once the browser window is adjusted

Having some issues while testing out the Highcharts javascript charting library on a specific page. The problem I'm encountering is that none of the data appears until I adjust the browser's size slightly. Prior to resizing, the tooltip does dis ...

Invoke a component's function in a different component

Upon clicking the button, I am trying to execute the 'exportHistoryToCSV' method within this component, which in turn calls a method from another component. However, I am encountering an error. @UntilDestroy() @Component({ selector: 'd ...

Is there a way to effectively eliminate an array of objects in JavaScript or TypeScript and alter the object structure simultaneously?

I am seeking solutions to restructure an object that has multiple arrays of objects so that I can access the object directly. console.log(value.data.summary[0].data) Instead of accessing arrays in this manner, I want to modify my data structure. Is there ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

Tips for selecting an image from the gallery with IONIC 3

Looking for guidance on extracting an image from the gallery in IONIC 3? I attempted to grab an image from the gallery but encountered some issues. Visit this link for more information This resource may also be helpful ...

Exploring the integration of LeafLet into Next JS 13 for interactive mapping

I'm currently working on integrating a LeafLet map component into my Next JS 13.0.1 project, but I'm facing an issue with the rendering of the map component. Upon the initial loading of the map component, I encountered this error: ReferenceError ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

When utilizing HttpParams in Angular 2 for an HTTP GET request, a 404 error is returned

I seem to be having a trouble with calling a GET endpoint from an Angular UI. I am trying to pass a timestamp as a parameter to the endpoint. Initially, I approached it in a basic way: return this.http.get(this.Uri + academyId + "?dateWhenToCalcula ...

Update the status of the reactive form control to invalid

I'm attempting to mark a form control as invalid, however, the following code snippet is not producing the desired result this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true}) ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

Resetting md-radio-button choices within an Angular 2 application

My Angular app has a sorting filter using radio buttons via md-radio-group for users to choose how they want data displayed. The radio buttons work fine, but I'm struggling to clear them when the "Restore Defaults" button is clicked. This is the code ...

What is causing my method chain to return a Promise<Promise<boolean?>> when using browser.wait(ExpectedConditions.presenceOf())?

Currently, I am in the process of creating some protractor tests that look like this: import { browser, element, by, ExpectedConditions } from 'protractor'; export class SomePage { private elements: any = {}; navigateToUpdate(name: string) ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Angular - Bootstrap modal displays as a standalone element rather than a dialog box

Currently working on my initial Angular project, I am attempting to incorporate a dialog that prompts for confirmation before deleting an item. Utilizing ng-bootstrap, I referred to the examples in the documentation as my starting reference. The issue I a ...

TS will not display an error when the payload is of type Partial

Why doesn't TypeScript throw an error when making the payload Partial? It seems to only check the first value but not the second one. type UserState = { user: User | null; loading: boolean; error: Error | null } type UserAction = { type: type ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...