I’m trying to display Google Analytics charts using the embed API with data that is being returned. I am currently returning the data from 3 different pages which works great. But is there a way of viewing that data in 3 separate charts?
This is the code that returns the results
var query = {
ids: VIEW_ID,
metrics: 'ga:avgTimeOnPage,ga:bounceRate,ga:pageviews,ga:sessions',
dimensions: 'ga:date,ga:pagePath',
filters: ‘ga:pagePath=@page1, ga:pagePath=@page2, ga:pagePath=@page3’ <!—page data returned
}
var report = new gapi.analytics.report.Data({ query });
report.on('success', function(response) {
//console.log(response);
});
report.execute();
I then want to display 3 different charts using the embed API. And switch between the charts using select> option elements. At the minute the id is being passed through and displaying all accounts, properties, and views.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector-container'
});
// Render the view selector to the page.
viewSelector.execute();
var chart = new gapi.analytics.googleCharts.DataChart({
query: {
ids: VIEW_ID,
dimensions: 'ga:date',
metrics: 'ga:avgTimeOnPage,ga:bounceRate,ga:pageviews,ga:sessions',
filters: ‘ga:pagePath=@page1, ga:pagePath=@page2, ga:pagePath=@page3’ <!—page data returned
},
chart: {
type: 'LINE',
container: 'line-chart',
options: {
fontSize: 12,
width: '100%',
colors: ['#4490BA', '#38A240', '#BD5065', '#BB8A21']
}
}
});
chart.on('success', function(response) {
});
viewSelector.on('change', function(ids) {
chart.set({ query: { ids: VIEW_ID }}).execute();
});
The above returns every account, property and all website data. I just want the data of the 3 different pages. Is this possible?
OK, so I managed to work it out myself.
I have my html elements which the charts get appended to from the Google script
<div id="line-chart-1"></div>
<div id="line-chart-2"></div>
<div id="line-chart-3"></div>
Then I created an array of where the page URLS get added to. Then looped through the array X amount of times which generated, in this case, 3 different charts; one for each page.
var valueArray = ['page1-url', page2-url, 'page3-url'];
for (var i = 0; i < valueArray.length; i++) {
var num = i + 1;
var chart = new gapi.analytics.googleCharts.DataChart({
query: {
ids: VIEW_ID,
dimensions: 'ga:date',
metrics: 'ga:avgTimeOnPage,ga:bounceRate,ga:pageviews,ga:sessions',
filters: valueArray[i]
},
chart: {
type: 'LINE',
container: 'line-chart-' + num,
options: {
fontSize: 12,
width: '100%',
colors: ['#4490BA', '#38A240', '#BD5065', '#BB8A21']
}
}
});
chart.on('success', function(response) {});
chart.execute();
}