How to customize google chart with hyperlink in the label?

前端 未结 1 456
鱼传尺愫
鱼传尺愫 2021-01-25 06:41

I have different countries which I get with json and add to google charts. Each country has a link to a specific site. It works for me. But the name of the tooltip/label is a li

相关标签:
1条回答
  • 2021-01-25 07:39

    first, recommend not using jsapi to load the library

    according to the release notes...

    The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.

    <script src="https://www.gstatic.com/charts/loader.js"></script>
    

    this will only change the load statement, to...

    google.charts.load('current', {
      callback: drawVisualization,
      packages:['geochart']
    });
    

    (the callback can be added to the load statement as well)


    next, according to the data format for regions mode,

    the second column should be a number (not a string / link)

    but since the link is needed for the click handler, use a DataView to hide the column from the chart

    ^ this will fix the tooltip -- adding the name of the country instead of the link

    the number column drives the shading of the country, according to the colorAxis

    if no number is provided, as in the question, then colorAxis will have no effect


    last, there are no standard options to control the country border

    see following working snippet...

    google.charts.load('current', {
      callback: drawVisualization,
      packages:['geochart']
    });
    
    function drawVisualization() {
      var data = google.visualization.arrayToDataTable([
        ['Country','Link',],
        ['Canada','http://www.google.ca'],
        ['Russia','http://www.bbc.com'],
        ['Australia','http://www.nytimes.com'],
      ]);
    
      var view = new google.visualization.DataView(data);
      view.hideColumns([1]);
    
      var options = {
        backgroundColor: '#81d4fa',
        datalessRegionColor: '#f8bbd0',
        defaultColor: 'black',
        displayMode: 'regions',
        tooltip: {textStyle: {color: '#FF0000'}, trigger:'focus',isHtml: true},
        legend: 'none',
        height:300,
        width:400
      };
    
      var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
      google.visualization.events.addListener(chart, 'select', myClickHandler);
      chart.draw(view, options);
    
      function myClickHandler(){
        var selection = chart.getSelection();
        if (selection.length > 0) {
          var link = data.getValue(selection[0].row, 1);
          window.open(link, '_blank');
        }
      }
    }
    <script src="https://www.gstatic.com/charts/loader.js"></script>
    <div id="visualization"></div>

    0 讨论(0)
提交回复
热议问题