Google Visualization GeoMap with Google Analytics - google-visualization

Ok, so I'm really hoping someone can help me get started, I have been able to plot pies and timelines from my google analytics data via api with google visualization. I now want to extract the data from google analytics of visits and plot a geomap. This is the geomap sample code which works
google.load('visualization', '1', {packages: ['geochart']});
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700],
['South Africa', 800]
]);
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, {width: 556, height: 347});
}
google.setOnLoadCallback(drawVisualization);
but of course I want to get the var 'data' from my google analytics api into such an array and plot say the top 10 popular countries based on pageviews from the last 30 days?
I believe the following query will give me what I want
dimensions=ga:country
metrics=ga:visits
sort=-ga:visits
How do I get this into the proper format for the data variable to plot this geomap? If you can help me rewrite the var data so that it works, I could be the happiest man alive.
Thanks in advance

This function should take the data returned by Google Analytics, input it into a DataTable, and draw a GeoChart of the top 10 countries by visit count:
function drawChart(results) {
var entries = results.feed.getEntries();
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Visits');
for (var i = 0; i < entries.length; i++) {
data.addRow([entries.getValueOf('ga:country'), parseInt(entries.getValueOf('ga:visits'))]);
}
// sort by visits, descending
var sortedRows = data.getSortedRows([{column: 1, desc: true}]);
// remove all elements after the 10th
while (sortedRows.length > 10) {
sortedRows.splice(10, 1);
}
var view = new google.visualization.DataView(data);
view.setRows(sortedRows);
var geochart = new google.visualization.GeoChart(document.getElementById('visualization'));
// draw the chart using the view
geochart.draw(view, {width: 556, height: 347});
}

You should look into using the new Google Analytics SuperProxy, it simplifies the process of getting api queries into the charts api, there are still a few bugs but very simple to setup, the youtibe video on the link below will take you through the full process. https://developers.google.com/analytics/solutions/google-analytics-super-proxy

Related

Google Geochart: Highlighting by continent & country (multiple resolutions)

I would like to make a google chart that highlights different regions continents, or countries based on a particular grouping.
The problem is I can't figure the best way to show both continents and countries.
For instance, I'd like to have two highlighted entries: Europe and Japan.
I can use the below JS code to attempt this:
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['150', 1, 'Europe'],
['Japan', 2, 'Japan']
]);
var options = {
resolution: 'continents',
}
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, options);
};
The above code partly works- Europe is properly highlighted and labelled. However, because resolution is set to 'continents' Japan does not get highlighted. If I set resolution to 'countries' the opposite problem occurs.
So the real question:
Is there a way to highlight both Europe and Japan individually with one array entry each, or do I have to put every single European country in the list to also have Japan highlighted?
yes, you would need to put every single European country in the list to also have Japan highlighted
another option might be to draw two charts, one on top of the other,
using the following config options to allow the bottom one to show thru.
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
however, this would suppress the tooltip on the bottom chart.
see following working snippet for an example...
google.charts.load('current', {packages:['geochart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['150', 1, 'Europe']
]);
var options1 = {
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
resolution: 'continents'
}
var geochart1 = new google.visualization.GeoChart(
document.getElementById('visualization1')
);
geochart1.draw(data1, options1);
var data2 = google.visualization.arrayToDataTable([
['Region', 'Label', {role: 'tooltip', p:{html:true}}],
['Japan', 2, 'Japan']
]);
var options2 = {
backgroundColor: 'transparent',
datalessRegionColor: 'transparent',
resolution: 'countries'
}
var geochart2 = new google.visualization.GeoChart(
document.getElementById('visualization2')
);
geochart2.draw(data2, options2);
}
.geo {
left: 0px;
position: absolute;
top: 0px;
width: 100%;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="geo" id="visualization1"></div>
<div class="geo" id="visualization2"></div>
note: jsapi should no longer be used to load the charts library,
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. The last update, for security purposes, was with a pre-release of v45. Please use the new gstatic loader.js from now on.
this will only change the load statement, see above snippet...

google chart obtaining position in select event listener

I have the following google chart:
var elms=xml.getElementsByTagName("overall")[0];
var avgs=elms.getElementsByTagName("average");
for(var i=0;i<avgs.length;i++){
chartArr[0][i+1]=avgs[i].getAttribute("name");
chartArr[1][i+1]=parseFloat(avgs[i].getAttribute("avg"));
}
var data = google.visualization.arrayToDataTable(chartArr);
var options = {
title: 'Average Club Rating',
is3D: true,
width:1200,
chartArea:{
width:800,
left:92
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('averagechart'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', function() {
console.log(this.getPosition());
});
If you look, i first populate the charArr then i create and setup the google chart.
On the bottom, you'll see the addListener call. What I want is when that element is clicked, a custom url most likely from the chartArr is used and determines the endpoint location.
How do I get the position of the listener so i can grab the custom url which is going to be created.
I dont really sure to understand your request, but you can print the event with this method,
console.log(chart.getSelection());
Regards,

Marking an address in geochart from its name

I am working on geochart.Is there any example showing how to mark a place,given only its name? I have done the same with geocoordinates,and with city names,country names with pure javascript
It depends on if Google knows where your place names are. For instance, this code will create a map with no problem of all the locations stated. Give it a try with your data and see if it plots:
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Place', 'Popularity'],
['Statue of Liberty', 200],
['Eiffel Tower', 300],
['Big Ben', 400],
['Tokyo Tower', 500],
['Great Pyramids', 600],
['Gobi Desert', 700]
]);
var geochart = new google.visualization.GeoChart(
document.getElementById('visualization'));
geochart.draw(data, {width: 556, height: 347, displayMode: 'markers'});
}
While it looks like the Statue of Liberty didn't plot, it's on there, it's just small and pinkish

GEO Chart Legend/Datatable

I'm wondering if it's possible to display a kind of data table in GEO Charts. I have this code:
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Count');
data.addRow(["AT",141]);
data.addRow(["BE",8]);
data.addRow(["CH",42]);
data.addRow(["DE",98]);
data.addRow(["ES",942]);
data.addRow(["GR",30]);
data.addRow(["HQ",104]);
data.addRow(["HU",30]);
data.addRow(["LU",10]);
data.addRow(["NL",153]);
data.addRow(["PL",53]);
data.addRow(["PT",102]);
data.addRow(["RU",266]);
data.addRow(["SE",13]);
data.addRow(["TR",228]);
var options = {
displayMode: 'regions',
region: '150',
colorAxis: {colors: ['#ffa3b5', 'red']},
tooltip: { textStyle: { fontName: '"Verdana"', fontSize: 14 } },
legend: {textStyle: {color: 'black', fontSize: 10}},
keepAspectRatio: false,
height: 300,
width: 550
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div_02'));
chart.draw(data, options);
}
As I have some special countries (like HQ) and Turkey (that is not in region 150), I would like to a datatable or legend to the geochart.
Is this possible or do I have to make a table charts and put it somewhere else on the website?
Cheers & Thx in Advance
Alex
You cannot add a dataTable to the geoChart using the native Google Visualization API. A GeoChart is a GeoChart and a DataTable is a DataTable. However, you can create a linked GeoChart and DataTable on the same page using the same data taking advantage of the Dashboard controls and chartwrappers.
If you get fancy with your CSS, you can even hover the <div> with the table over the GeoChart, or otherwise find a way to make it look like they are the same chart.

Is there an exiting js method/library to convert regular json objects to google visualization type of js objects?

we have existing rest web services that generates json response. now we want to use google charts to show those data. google visualization api seems to expect its own json format. Is there any exiting js method/library to convert regular json objects to google visualization type of js objects? Thanks.
It really depends on what you're aiming for and what data looks like, and the google chart you want to use. I usually do the following when working with REST data and google charts.
In this example I use jQuery, but the js library you use isn't that relevant.
Say you've got the following set of data and what to show it in an areachart:
{"events":[{"event":{"timestamp":"1310926588423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926578423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926568423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926558423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926548423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926538423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926528423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926518423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926508423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}},{"event":{"timestamp":"1310926498423","service":"EsperEventProcessor.service","countAll3Sec_EsperEventProcessor":"0","server":"EsperServer"}}]}
To do this with JQuery and JSONQuery (which can help in easy selecting specific content in your JSON data) you can do something like this:
// use the getJSON jQuery operation to get the REST data
$.getJSON(restURL, function(data) {
// use jsonquery to get all the 'event's from the JSON data
var query1 = "..event";
var rootEvent = JSONQuery(query1,data);
// manually create a datatable and fill it in the required
// way for this chart
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Number of queries / per 10 seconds');
data2.addColumn('number', '# queries');
// each row is added based on information from the json event
// by simply iterating over the array
data2.addRows(rootEvent.length);
for (i = 0; i < rootEvent.length; i++) {
var date = new Date(parseInt(rootEvent[i]['timestamp']));
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var time = '';
if (hours < 10) time=time+'0'; time=time+hours+':';
if (minutes < 10) time=time+'0'; time=time+minutes+':';
if (seconds < 10) time=time+'0'; time=time+seconds;
data2.setCell(i,0,time);
data2.setCell(i,1,parseInt(rootEvent[i]['countAll3Sec_EsperEventProcessor']));
}
chart.draw(data2, {width: 400, height: 240, title: 'Requests per 10 seconds',
hAxis: {title: 'Time', titleTextStyle: {color: '#FF0000'}}
});
});