Reputation: 2231
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.
Upvotes: 0
Views: 242
Reputation: 369
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
Upvotes: 3