Google Analytic Embed API chart: Responsive

ぃ、小莉子 提交于 2019-12-23 04:16:14

问题


How would I make this Google Analytic Embed API chart responsive? I noticed that the demo on this page is reponsive: https://ga-dev-tools.appspot.com/embed-api/basic-dashboard/

I have also seen various ways of doing this with Google Charts here https://code.google.com/p/google-visualization-api-issues/issues/detail?id=1056

<!doctype html>
<html lang="en">
<head>
<title>Google Charts</title>


    <script>
    (function(w,d,s,g,js,fs){
        g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
        js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
        js.src='https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
    }(window,document,'script'));
    </script>

    <script>

    gapi.analytics.ready(function() {
    var ACCESS_TOKEN = 'XXX'; // obtained from your service account

    gapi.analytics.auth.authorize({
        serverAuth: {
        access_token: ACCESS_TOKEN
        }
    });

    var linechart = new gapi.analytics.googleCharts.DataChart({
    query: {
    ids: 'ga:XXXXXX',
    metrics: 'ga:users',
    dimensions: 'ga:date',
    'start-date': '30daysAgo',
    'end-date': 'yesterday'
      },
    chart: {
    type: 'LINE',
    container: 'line-chart',
    options: {
        width: '100%',
        title: 'Test.com: Visitors over the past 30 days.',
        fontSize: 12
        }
    }
    });

    linechart.on('success', function(response) {
    // response.chart : the Google Chart instance.
    // response.data : the Google Chart data object.
    });

    linechart.execute();        

    });

    </script>

</head>

<body>
                <div>
                    <div id="embed-api-auth-container"></div>
                    <div id="line-chart" style='width:100%;height:300px;'></div>

                </div>    

</body>
</html>

回答1:


I answered this over here

(Google Embed API) How to change chart-table-style width

Basically you just add an option element and assign width of x% within the charts option element




回答2:


I just noticed the same issue, setting:

options: {
   width: '100%'
}

doesn't work when document width changes (only 'TABLE' chart is responsive 'out of the box').

As workaround, you need to trigger a chart redraw on window resize:

window.addEventListener('resize', function() {
    linechart.execute();
});

Sidenotes:

  • linked Google page doesn't seems to use this or whatelse workarounds to have the chart responsive but the behavior is the same;
  • if you have animations enabled in your chart those animations might be played multiple times on window resize;


来源:https://stackoverflow.com/questions/27556273/google-analytic-embed-api-chart-responsive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!