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

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'}}
});
});

Related

How to use more than 3 column data with Google GeoChart

I am working on data visualization and want to show average wage and Estimated population on EVERY state of US. Now I am using google geochart for this part and I almost get the work done.
But I found out google geo chart doesn't support data which contains more than 3 columns.
Below is my work and how it looks when I run it.
function drawNewChart(){
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'my key'
});
google.charts.setOnLoadCallback(function(){
let map_data = [['State', 'Count', 'AvgWages']]
Object.getOwnPropertyNames(stateData).forEach(function(item, index){
map_data.push(['US-' + item, stateData[item].count, stateData[item].AvgWages / stateData[item].count])
})
console.log('full data', map_data)
var data = google.visualization.arrayToDataTable(map_data);
var options = {
region: "US",
resolution: "provinces"
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
With 3 columns it works fine and it shows this.
However I want to add 1 more column to it. (EstimatedPopulation). When I add this then it shows this error message:
Incompatible data table: Error: Table contains more columns than expected (Expecting 3 columns)
How can I solve this problem ?
Here are few solutions for your query
https://codesandbox.io/s/xjqrk659zw?file=/src/index.js:847-892
You need to define
tooltip: { isHtml: true, trigger: "visible" }
in the options
And then
{ role: "tooltip", type: "string", p: { html: true } }
in your data parameter.
Hope it will help

powerbi global object not found in typescript

I am trying to use this power bi below code where powerbi object not found error is getting in my typescript code:
// Read embed application token from textbox
var txtAccessToken = $('#txtAccessToken').val();
// Read embed URL from textbox
var txtEmbedUrl = $('#txtReportEmbed').val();
// Read report Id from textbox
var txtEmbedReportId = $('#txtEmbedReportId').val();
// Read embed type from radio
var tokenType = $('input:radio[name=tokenType]:checked').val();
// Get models. models contains enums that can be used.
var models = window['powerbi-client'].models;
// We give All permissions to demonstrate switching between View and Edit mode and saving report.
var permissions = models.Permissions.All;
// Embed configuration used to describe the what and how to embed.
// This object is used when calling powerbi.embed.
// This also includes settings and options such as filters.
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
var config= {
type: 'report',
tokenType: tokenType == '0' ? models.TokenType.Aad : models.TokenType.Embed,
accessToken: txtAccessToken,
embedUrl: txtEmbedUrl,
id: txtEmbedReportId,
permissions: permissions,
settings: {
filterPaneEnabled: true,
navContentPaneEnabled: true
}
};
// Get a reference to the embedded report HTML element
var embedContainer = $('#embedContainer')[0];
// Embed the report and display it within the div container.
var report = powerbi.embed(embedContainer, config);
// Report.off removes a given event handler if it exists.
report.off("loaded");
// Report.on will add an event handler which prints to Log window.
report.on("loaded", function() {
Log.logText("Loaded");
});
report.on("error", function(event) {
Log.log(event.detail);
report.off("error");
});
report.off("saved");
report.on("saved", function(event) {
Log.log(event.detail);
if(event.detail.saveAs) {
Log.logText('In order to interact with the new report, create a new token and load the new report');
}
});
in the above code the powerbi object shows not found in my typescript code: powerbi.embed(embedContainer, config);
I tried to use window['powerbi'] or window.powerbi but doesn't work. What should be the solution then?
I faced a similar issue a few weeks back (probably exactly the same). For me it seems that what works is using window.powerbi.embed() for the embed action, whereas the import import * as powerbi from "powerbi-client"; is used for all other Power BI objects.
I had the same problem, found this question through a google search. I wasn't able to figure out why it wasn't on the window, but as a work around you can initialize it yourself like this:
import * as pbi from "powerbi-client";
const powerbi = new pbi.service.Service(
pbi.factories.hpmFactory,
pbi.factories.wpmpFactory,
pbi.factories.routerFactory
);
const container = document.getElementById("report-container");
powerbi.embed(container, embedConfiguration);

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,

Google Visualization GeoMap with Google Analytics

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

google chart Json response within 1 sec but still get timeout after 30 sec and no "pause on exception"

I've tested this code in various constellations and only one of the constellations is giving me an error that I can't track down yet. Maybe someone else with more google-visualization experience can see the problem. In this one case, get the json resonse, then I get a token error with no token identified in the error message and "paus on error" does not pause anywhere in my js nor in external js. Then, after 30 sec. my callback is indeed called but with the error set to timeout (error in query).
Here is the URL which you can also test without SSL
https://cio-services.eu/demoOe2/Api/Insight/GetESiteEuoChart/?viewFlag=1&eSiteKid=4b92d450-b29d-47c0-943b-00890f56caf2&periodMin=7200&keyProp=KW15
Here is my client js which works in several scenarios
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var chartOptions = {
curveType: 'none',
//width: 1200,
height: 400,
vAxis: { maxValue: 10, title: 'kWh/4 (15 min)' },
hAxis: { title: 'Time' },
title: 'Live production log',
titlePosition: 'out',
titleTextStyle: { fontSize: 14, textIndent: 10 },
fontSize: 12
};
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var _chart;
function drawChart() {
//GET GChart data
var query = new google.visualization.Query('https://cio-services.eu/demoOe2/Api/Insight/GetESiteEuoChart/?viewFlag=1&eSiteKid=4b92d450-b29d-47c0-943b-00890f56caf2&periodMin=7200&keyProp=KW15');
//set query parameters
//query.setQuery('select 1, 2');
query.send(drawTable);
}
function drawTable(response) {
//error checking
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + '' + response.getDetailedMessage());
return;
}
//convert response to JSON string
var googleDataQuery = response.getDataTable().toJSON();
//Convert JSON to google Data table
var convertedData = new google.visualization.DataTable(googleDataQuery, 0.5);
//Initialize a specific data table sub set view and store into a variable
var view = new google.visualization.DataView(convertedData);
_chart.draw(view, chartOptions);
}
$(function () {
_chart = new google.visualization.LineChart(document.getElementById('chart_div'));
});
</script>
OK, there is a bit of magic going on here that requires attentive reading of the doc to understand.
https://developers.google.com/chart/interactive/docs/dev/implementing_data_source
JSON Response Format
The default response format is JSON if the request includes an "X-DataSource-Auth" header, and JSONP otherwise. Note that the Google chart client actually supports a modified version of JSON and JSONP; if you are using the Java or Python helper libraries, they will put out the proper code for you; if you are parsing responses by hand, see JSON Modifications below
What happens is:
if you supply a target domain that in any way differs (even a different port) from the home domain, then google-visualization decides to remove the "X-DataSource-Auth" header property and thereby triggers the client to expect jsonP instead of json. Apparently the RequestID is also always zero in these cases. In any case, this means that you cannot simply reuse APIs for CORS and non-CORS access.
Just take a look at the http request header going out. If the Host: and Referer: properties differ in any way, then instead of returning pure json, you return something like this:
string returnVal = "google.visualization.Query.setResponse(" + my-valid-pure-json + ")";
Details here: https://developers.google.com/chart/interactive/docs/dev/implementing_data_source?hl=en
GG