Reputation: 35
I'm trying to extract the yesterdays visits from my website through the Google Analytics API.
I understand how to extract the data, but I don´t understand how to show the data in the browser.
var report = new gapi.analytics.report.Data({
query: {
'ids': 'ga:XXX',
'metrics': 'ga:visits',
'start-date': 'yesterday',
'end-date': 'yesterday',
}
});
report.execute();
Here is the query code. Can anyone help me with it with a working example?
Upvotes: 0
Views: 419
Reputation: 27
Assuming you are also referencing the relevant libraries for the analytics API and you have set up access tokens etc. Then you could change your code as below. Also, when you say 'browser' I'm assuming you're pointing this towards an HTML page. If so you'll need to put a div element in the page. Let's call this div element 'yesterdaySessions'. BTW, you also need to change your query from 'visits' to 'sessions' since this is what Google now call it.
So in your HTML page you need a div element like this:
<div id="yesterdaySessions"></div>
Then you need to modify your code to tell it to send your results from the GA API to your div element. This should then look something like this:
var report = new gapi.analytics.report.Data({
query: {
ids: 'ga:XXX', //change this for your profile.
'metrics': 'ga:sessions', // visits is now 'sessions'
'start-date': 'yesterday',
'end-date': 'yesterday',
}
});
// When the report has run you need to then send it to your div element created above.
report.on('success', function(report) {
for (var prop in report) {
var outputDiv = document.getElementById('yesterdaySessions');
outputDiv.innerHTML = report[prop];
}
//Optional, but it is worth logging your results to the console in case you later want to unpick what is going on.
console.log(report);
});
report.execute();
Bear in mind that the code above will send all parts of the returned array to the page element 'yesterdaySessions'. However, since there is just one integer value (the sessions from yesterday), this is what you will read. It is worth knowing that the entire array is there, mind you, because if you later want to manipulate it (for example add yesterday's visits to today's visits) you'll need to do something else to extract the values from the arrays.
Hope this helps.
Upvotes: 1