Skip to content Skip to sidebar Skip to footer

Google Charts (areachart) How To Detect Zoom Change

I am drawing an AreaChart, with some markers on an overlay. I am using the explorer option (horizontal only) in order to let the user zoom in and out. The problem is that I can't f

Solution 1:

rather than relying on events to detect zoom change

use a mutation observer, which will notify when elements have been added to the chart container

each time a zoom occurs, elements are added to the chart such as the background highlighting of the area selected when zoomed

see following working snippet, which uses a mutation observer to detect zoom, and change the color of the selection box...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable({
      "cols": [
        {"label": "X", "type": "number"},
        {"label": "Y", "type": "number"}
      ],
      "rows": [
        {"c": [{"v": 0}, {"v": 0}]},
        {"c": [{"v": 1}, {"v": 1}]},
        {"c": [{"v": 2}, {"v": 2}]},
        {"c": [{"v": 3}, {"v": 4}]},
        {"c": [{"v": 4}, {"v": 8}]},
        {"c": [{"v": 5}, {"v": 16}]},
        {"c": [{"v": 6}, {"v": 32}]},
        {"c": [{"v": 7}, {"v": 64}]},
        {"c": [{"v": 8}, {"v": 128}]},
        {"c": [{"v": 9}, {"v": 256}]}
      ]
    });

    var options = {
      explorer: {
        actions: ['dragToZoom', 'rightClickToReset'],
        axis: 'horizontal',
        keepInBounds: true
      },
      hAxis: {
        title: 'X'
      },
      vAxis: {
        title: 'Y'
      }
    };

    var chartDiv = document.getElementById('chart_div');
    var chart = new google.visualization.LineChart(chartDiv);

    var observer = newMutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        mutation.addedNodes.forEach(function (node) {

          // adjust overlays hereif (node.getAttribute('fill') === '#0000ff') {
            node.setAttribute('fill', '#00ff00');
          }

        });
      });
    });
    observer.observe(chartDiv, {
      childList: true,
      subtree: true
    });

    chart.draw(data, options);
  },
  packages:['corechart']
});
<scriptsrc="https://www.gstatic.com/charts/loader.js"></script><divid="chart_div"></div>

Post a Comment for "Google Charts (areachart) How To Detect Zoom Change"