Creating a custom metric for Google Analytics - javascript

I have embedded the Google Analytics API to my website (developed using php, yii2 framework). I would like to create a custom metric to include in my chart. The value for my custom metric would be from my database. From the documentation, I tried using the following snippet:
var metric1Value = <?= $modelValue; ?>
ga('set', 'metric1', metric1Value);
This however results in an error stating that 'ga' is undefined. Is it even possible to create a custom metric in Google Analytics? If it is, how can it be achieved?
Here's an overview of my code if it helps. I've followed the tutorial:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div>Analytics Test</div>
<div id="embed-api-auth-container"></div>
<div id="view-selector-container" style="display:none;"></div>
<div id="date-range-selector-container"></div>
<div id="table-container" style="margin:5%"></div>
<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'));
gapi.analytics.ready(function() {
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: 'myclientid'
});
var dataChart = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'start-date':'50daysAgo',
'end-date':'yesterday',
'metrics': [['ga:sessions', 'ga:users', 'ga:newUsers', 'ga:pageviews']],
'dimensions': [['ga:date']],
},
chart: {
container: 'table-container',
type: 'TABLE',
options: {
width: '80%'
}
}
});
});
</script>
Any help would be greatly appreciated.

Syntax you're using is for tracking custom metric on your website, and code you're using is for showing report data. If you want to show custom metric then add ga:metric1 in your metric list
e.g.
'metrics': [['ga:sessions', 'ga:users', 'ga:newUsers', 'ga:pageviews']]
will be
'metrics': [['ga:sessions', 'ga:users', 'ga:newUsers', 'ga:pageviews', 'ga:metric1']]
Note: Your metric needs to be configured in Google Analytics Account Panel

Related

Adding multiple Google Analytics charts on the same page

I have a dashboard in which I need to incorporate Google Analytics charts. Each chart is a different widget and can be removed from or added to the dashboard. The charts display properly when there is only ONE added to the dashboard. When I add two, they don't display anything anymore. Could the fact that I call the same Embed API library in each widget cause this?
An example of the code I am using for each widget:
<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>
<div id="embed-api-auth-container-1"></div>
<div id="chart-container-1"></div>
<div id="view-selector-container-1"></div>
<script>
gapi.analytics.ready(function() {
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container-1',
clientid: '***'
});
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector-container-1'
});
viewSelector.execute();
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
container: 'chart-container-1',
type: 'LINE',
options: {
width: '100%'
}
}
});
viewSelector.on('change', function(ids) {
dataChart.set({query: {ids: ids}}).execute();
});
});
</script>
Managed to temporarily fix this by calling the Embed API library ONLY in the first widget that appears on the page. Not ideal, but it works for now. If anybody figures out the right solution, I'd like to know.

No data when rendering ga:userGender in my app using Reporting API V4

I am creating simple app that renders Google Analytics data in view.
By using multiple examples I have set up everything. Few queries work without problem, but I can't retrieve info about audience, especially, userGender.
I don't receive any error message in view, but just "No data" message.
My code in view:
<div id="chart-2-container"></div>
<div id="view-selector-2-container"></div>
<script>
var viewSelector2 = new gapi.analytics.ViewSelector({
container: 'view-selector-2-container'
});
viewSelector2.execute();
var dataChart2 = new gapi.analytics.googleCharts.DataChart({
query: {
metrics: 'ga:users',
dimensions: 'ga:userGender',
'start-date': '60daysAgo',
'end-date': 'today',
'max-results': 6,
},
chart: {
container: 'chart-2-container',
type: 'PIE',
options: {
width: '100%',
pieHole: 4/9
}
}
});
viewSelector2.on('change', function(ids) {
dataChart2.set({query: {ids: ids}}).execute();
});
</script>
Note: I just showed code for that query that doesn't work, I have other ones that work great (See attached pic):
I tried the same query in query-explorer and received no data message too.
In Audience - Dimensions & Metrics Explorer under ga:userGender dimension isn't requered any metrics, but in Query Explorer they required metric (See in above example).
What could be possible problem and solution for this?
Thanks.

google analytics embed api authentication with access token

Hi all
I am new for google analytics embed api. And I am trying to use access token in order to get data without user consent. I've got a Key for browser applications in google developer console. But I couldn't figure out how to use it. Here is my code. It doesn't work (I've set the reference to any reference allowed):
Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Embed API Demo</title>
</head>
<body>
<!-- Step 1: Create the containing elements. -->
<section id="auth-button"></section>
<section id="view-selector"></section>
<section id="timeline"></section>
<!-- Step 2: Load the library. -->
<script>
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
</script>
<script>
gapi.analytics.ready(function() {
// Step 3: Authorize the user.
gapi.analytics.auth.authorize({
serverAuth: {
access_token: 'XXXXX' // do not share sensible data
}
});
// Step 4: Create the view selector.
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
// Step 5: Create the timeline chart.
var timeline = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:date',
'metrics': 'ga:sessions',
'start-date': '30daysAgo',
'end-date': 'yesterday',
},
chart: {
type: 'LINE',
container: 'timeline'
}
});
// Step 6: Hook up the components to work together.
gapi.analytics.auth.on('success', function(response) {
viewSelector.execute();
});
viewSelector.on('change', function(ids) {
var newIds = {
query: {
ids: ids
}
}
timeline.set(newIds).execute();
});
});
</script>
</body>
</html>

Meteor, Iron Router, & Google Analytics Embed API

After trying to authenticate Google API calls through Meteor's accounts-google package, I decided to try Analytics' Embed API to cut down on some complexity. I've been able to get individual dashboards working by loading the client library, authenticating, etc. on each template, but of course that's inefficient and filled with repetition.
What's the best way to load the Embed API library, authentication, and view selector once while allowing templates to detect them as they're loaded with Iron Router? Or am I simply forcing Meteor into an application it's not well-suited for?
I've added some sample code to give an idea of how things are structured now:
/client/layout.html
<template name="layout">
<header>
<h1>DDDashboard</h1>
</header>
<section id="admin">
<div id="auth-button"></div> <!-- Outlet for Embed API's auth -->
{{> view}} <!-- Outlet for the View template -->
</section>
<section id="main">
{{> yield}} <!-- Outlet for each dashboard -->
</section>
</template>
/client/view.html
This template is used in a Template.foo.rendered to prevent the dashboard from loading until the Embed API view selector is fully instantiated.
<template name="view">
<div id="view-selector"></div>
</template>
/client/basic.html
Generic example of a dashboard—the Embed API relies on predefined elements to render into. More complex dashboards would have more <div> to contain other charts/info.
<template name="basic">
<div id="data-container"></div> <!-- Outlet for the Embed API chart -->
</template>
/lib/router.js
Router.configure({
layoutTemplate: 'layout'
});
Router.route('/', {
name: 'basic'
});
/client/lib/gapi.js
Loads the Google Embed API library at launch.
(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'));
/client/auth.js
gapi.analytics.ready(function(){
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: 'INSERT-CLIENTID'
});
});
/client/view.js
Once the Embed API library is fully loaded, the view selector is created as a global variable so any chart or data objects can access it.
gapi.analytics.ready(function(){
viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
viewSelector.execute();
});
/client/basic.js
Uses Template.foo.rendered to wait for the view selector to load; if it doesn't, the chart div remains empty. This dashboard contains one chart; others would contain many but more or less the same pattern.
Template.view.rendered = function(){
gapi.analytics.ready(function(){
var dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
container: 'data-container',
type: 'LINE',
options: {
width: '100%'
}
}
});
viewSelector.on('change', function(ids){
dataChart.set({query: {ids: ids}}).execute();
});
});
};
Turns out to be pretty simple—just needed to add some Meteor sugar to get things behaving properly. Simple explanation: on a change from the viewSelector, set the current view as a Session variable; then add Tracker.autorun() blocks to grab updates and have the chart update itself. Also, be aggressive using Template.view.created callbacks to ensure objects load in the right order and aren't being rendered multiple times.
/client/view.js
Template.view.created = function(){
gapi.analytics.ready(function(){
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector'
});
viewSelector.execute();
viewSelector.on('change', function(ids){
Session.set('currentView', ids);
});
});
};
/client/basic.js
Template.users.created = function(){
gapi.analytics.ready(function(){
dataChart = new gapi.analytics.googleCharts.DataChart({
query: {
metrics: 'ga:users',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
container: 'data-container',
type: 'LINE',
options: {
width: '100%'
}
}
});
Tracker.autorun(function(){
if(Session.get('currentView')){
dataChart.set({query: {ids: Session.get('currentView')}}).execute();
}
});
});
};
I'm sure there's room to improve with this pattern—wrapping each session variable into a Tracker.autorun() block on every dashboard seems a little superfluous, but keeping all the selectors and data objects locally-scoped is probably a but more secure and resistant to user tampering. Also works with date selection.

Google Analytic Embed API chart: Responsive

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>
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
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;
I was using google analytics API and I had the same issue but it worked for me by adding
options:{width:'100%'}
chart: {
type: 'LINE',
container: 'timeline',
options: {width: '100%'}
}

Categories

Resources