2016年1月7日 星期四

[Google] Google Analytics Api 使用教學4 (step by step) 最終回


前言 : 快點給我看結果吧!!!

步驟一 : 我們使用Google 的 Embed API 來呈現,這是官網,裡面有很多相關介紹,尤其是左下方的Query Exploer 可以讓你線上測試自己的搜尋內容唷!!

2016-01-07_175958

步驟二 :  點擊左邊的 Server-side Authorization 裡面的HTML內容設置即可,或是參考下面程式範例 :

<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>
 // 更多api 設定
 // https://developers.google.com/analytics/devguides/reporting/core/dimsmets
 gapi.analytics.ready(function() {

   /**
    * Authorize the user immediately if the user has already granted access.
    * If no access has been created, render an authorize button inside the
    * element with the ID "embed-api-auth-container".
    */
   gapi.analytics.auth.authorize({
  'serverAuth': {
                                'access_token': '從後台得到的token'
                            }
   });


   /**
    * Create a new ViewSelector instance to be rendered inside of an
    * element with the id "view-selector-container".
    */
   var viewSelector = new gapi.analytics.ViewSelector({
  container: 'view-selector-container'
   });

   // Render the view selector to the page.
   viewSelector.execute();


   /**
    * Create a new DataChart instance with the given query parameters
    * and Google chart options. It will be rendered inside an element
    * with the id "chart-container".
    */
   var dataChart = new gapi.analytics.googleCharts.DataChart({
  query: {
    metrics: 'ga:sessions',
    dimensions: 'ga:date',
    'start-date': '30daysAgo',
    'end-date': 'yesterday'
  },
  chart: {
    container: 'chart-container',
    type: 'LINE',
    options: {
   width: '100%'
    }
  }
   });


   /**
    * Render the dataChart on the page whenever a new view is selected.
    */
   viewSelector.on('change', function(ids) {
  dataChart.set({query: {ids: ids}}).execute();
   });

 });
});
</script>

重點,記得把後台得到的token 放進 'access_token' 欄位!!!

然後基本的圖表就會出來囉!!!  終於!!!



ps.細節參數設定請參考此

沒有留言:

張貼留言