sgratzl / chartjs-chart-geo

Chart.js Choropleth and Bubble Maps
https://www.sgratzl.com/chartjs-chart-geo/
MIT License
347 stars 36 forks source link

Angular integration #236

Closed tomnar closed 3 months ago

tomnar commented 3 months ago

Is there an example on how to integrate this with angular? I could only find: https://github.com/sgratzl/chartjs-chart-geo/issues/23, but it is not working anymore. I have tried myself, but I get "choropleth" is not a registered controller.

Thank you for your help :)

Using: "angular": "^18.0.0" "chart.js": "^4.4.3", "chartjs-chart-geo": "^4.3.1", "ng2-charts": "^6.0.1",

nirajnandha commented 3 months ago

geo-chart.component.ts // src/app/geo-chart/geo-chart.component.ts import { Component, OnInit } from '@angular/core'; import { Chart, ChartData, ChartOptions, ChartType, registerables } from 'chart.js'; import { ChoroplethController, ColorScale, GeoFeature } from 'chartjs-chart-geo'; import * as d3 from 'd3-fetch';

// Register Chart.js components Chart.register(...registerables); Chart.register(ChoroplethController, ColorScale, GeoFeature);

@Component({ selector: 'app-geo-chart', templateUrl: './geo-chart.component.html', styleUrls: ['./geo-chart.component.css'] }) export class GeoChartComponent implements OnInit { public geoChartData: ChartData = { labels: [], datasets: [ { label: 'Countries', outline: {}, data: [] } ] };

public geoChartOptions: ChartOptions = { responsive: true, scales: { xy: { projection: 'equalEarth' } } };

public geoChartType: ChartType = 'choropleth';

constructor() { }

ngOnInit(): void { d3.json('https://unpkg.com/world-atlas@1/world/50m.json').then((countries: any) => { this.geoChartData.labels = countries.objects.countries.geometries.map((d: any) => d.id); this.geoChartData.datasets[0].outline = countries; this.geoChartData.datasets[0].data = countries.objects.countries.geometries.map((d: any) => ({ feature: d, value: Math.random() * 100 })); }); } }

geo-chart.component.html

// src/app/app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { NgChartsModule } from 'ng2-charts'; import { GeoChartComponent } from './geo-chart/geo-chart.component';

@NgModule({ declarations: [ AppComponent, GeoChartComponent ], imports: [ BrowserModule, NgChartsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

Geographical Chart using Chart.js, chartjs-chart-geo, and ng2-charts

tomnar commented 3 months ago

Aaand I just figured it out myself hehe. I was able to add it to the providers and now it works:

export const appConfig: ApplicationConfig = {
  providers: [
    ...
    provideCharts({ registerables: [CategoryScale, LinearScale, PointElement, LineElement, LineController, Filler, ChoroplethController, ProjectionScale, ColorScale, GeoFeature] }),
  ],
};