Reputation: 363
My question is: How do I load data from Google Analytics in a Chart.js chart?
I am writing a program with the Laravel framework (version 5.6) and use the Google Analytics API (not the Google Analytics Embed API)(version 3).
I get the data correctly presented in an array but I want to show it in a graph.
Subquestion: Do I need to replace the data in datasets with a connection to the Google Analytics API?
A simple chart from Chart.js:
<canvas id="userChart"></canvas>
<script>
var ctx = document.getElementById('userChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["dag 1", "dag 8", "dag 15", "dag 22", "dag 30"],
datasets: [{
label: "users",
//backgroundColor: '#2f5ec4',
borderColor: '#2f5ec4',
data: [138, 163, 115, 124, 49],
}]
},
// Configuration options go here
options: {}
});
Update: Example of how I get the Analytics data:
Route::get('/datatest', function()
{
$analyticsData =
Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
dd($analyticsData);
});
Example of the DD array:
Upvotes: 1
Views: 3154
Reputation: 176
It might be too late but for anyone who is in need, try the following. For your case you have your $analyticsData collection, which is a good start. Chartjs uses lists to map and compare data. So for example we want to see a chart of date vs visitors
//transfer all of this code out of the routes to your controller
$analyticsData = Analytics::fetchTotalVisitorsAndPageViews(Period::days(30));
//send these two variables to your view
$dates = $analyticsData->pluck('date');
$visitors = $analyticsData->pluck('visitors');
In your script, the labels should receive $dates in a list as follows;
labels: {!! json_encode($dates) !!},
And data in datasets receive $visitors as a list;
data: {!! json_encode($visitors) !!}
See this article on my website for more in-depth explanations.
Upvotes: 3