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

Fix the npm example #207

Closed zackees closed 4 months ago

zackees commented 11 months ago

The npm example in the readme is incomplete and doesn't work. Here's one that does.

<canvas id="canvas"></canvas>
import Chart from 'chart.js/auto';
import { ChoroplethController, GeoFeature, ColorScale, ProjectionScale, topojson } from 'chartjs-chart-geo';

// register controller in chart.js and ensure the defaults are set
Chart.register(ChoroplethController, GeoFeature, ColorScale, ProjectionScale);

const CANVAS_ID = "canvas"
const DATA_SOURCE = "https://unpkg.com/us-atlas/states-10m.json";

async function initDynamicContent() {
  try {
    const response = await fetch(DATA_SOURCE);
    const us = await response.json();

    const nation = topojson.feature(us, us.objects.nation).features[0];
    const states = topojson.feature(us, us.objects.states).features;

    const data = {
      type: 'choropleth',
      data: {
        labels: states.map((d) => d.properties.name),
        datasets: [{
          label: 'States',
          outline: nation,
          data: states.map((d) => ({feature: d, value: Math.random() * 10})),
        }]
      },
      options: {
        plugins: {
          legend: {
            display: false
          },
        },
        scales: {
          projection: {
            axis: 'x',
            projection: 'albersUsa'
          },
          color: {
            axis: 'x',
            quantize: 5,
            legend: {
              position: 'bottom-right',
              align: 'bottom'
            },
          }
        },
      }
    }

    const chart = new Chart(document.getElementById(CANVAS_ID).getContext("2d"), data);
  } catch (error) {
    console.error("Error fetching and processing data:", error);
  }
}

export async function initGeoChart () {
  await initDynamicContent();
}
sgratzl commented 4 months ago

the main examples of this plugin are either using https://codepen.io/sgratzl/pen/gOaBQep or available via https://www.sgratzl.com/chartjs-chart-geo/examples/