google chart obtaining position in select event listener - google-visualization

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,

Related

Attach onAnimationComplete for Chart.js after creation

I'm creating a Blazor component as a facade of ChartJs. I opened a question on the Microsoft forum to understand how I can call a JavaScript function for the component.
My problem is how to add some events to the chart before the creation. So, from the Blazor page, I pass a model called config that contains all the configuration for the chart.
Then, I create the chart in JavaScript like
var ctx = document.getElementById(id).getContext('2d');
var chart = new Chart(ctx, eval(config));
Now, I want to add an event and send to Blazor an event. For example, I added the following code for the event onHover and it works.
chart.options.onHover = function () {
DotNet.invokeMethodAsync('PSC.Blazor.Components.Chartjs', 'ChartHover');
}
With onClick is working too.
chart.options.onClick = function (event, array) {
var rtn = 0;
if (array !== undefined && array.length > 0)
rtn = array[0].index;
DotNet.invokeMethodAsync('PSC.Blazor.Components.Chartjs', 'ChartClick', rtn);
};
Now, I want to do the same with onAnimationComplete.
chart.onAnimationComplete = window["AnimationComplete1"];
In this cases, the function is not being called. Some if I write this code
chart.onAnimationComplete = function () {
console.log('onAnimationComplete animation completed');
};
How can I fix the code?
there is no onAnimationComplete event you can configure directly on the chart. This has to be done in the options like you did for the onHover and the name has to be different:
chart.options.animation.onComplete = function () {}

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

how to make google chart API work under asp.net PageRequestManger

I have a submit button and upon pressing the button I display a loading image and then draw table and then draw google chart.
code for google chart (this works - verified it standalone):
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['corechart']});
</script>
<script type='text/javascript'>
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['Year', 'Austria', 'Belgium', 'Czech Republic', 'Finland', 'France', 'Germany'],
['ENG 2001', 1336060, 3817614, 974066, 1104797, 6651824, 15727003],
['ENGLISH 2002', 1538156, 3968305, 928875, 1151983, 5940129, 17356071],
['ENGLISH2003', 1576579, 4063225, 1063414, 1156441, 5714009, 16716049]
])
new google.visualization.ColumnChart(document.getElementById('visualization')).
draw(data, {title:'Yearly Coffee Consumption by Country',
width:1000, height:600,hAxis: {title: 'Year'}, isStacked:true}
);
}
//google.setOnLoadCallback(drawVisualization);
</script>
code for loading image when pressing a submit button
<script type="text/javascript">
// Get the instance of PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Add initializeRequest and endRequest
prm.add_initializeRequest(prm_InitializeRequest);
prm.add_endRequest(prm_EndRequest);
// Called when async postback begins
function prm_InitializeRequest(sender, args) {
//Display the loading image
var panelProg = $get('divImage');
panelProg.style.display = '';
}
// Called when async postback ends
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$(document).ready(function () {
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
//draw google chart (doesnt work)
google.setOnLoadCallback(drawVisualization);
//or even doesnt work (assume comment out for google.setOnLoadCallback(drawVisualization);
drawVisualization();
});
}
</script>
my submit button is under update panel (to make partial-page refresh for loading image to show user that it's fetching data from server). with this code, i am able to show loading image and display table but not google chart. I am not sure how I can call google chart draw function to make google chart appear. I have looked at several posting but couldnt find anything that works for my case. I even tried google.load('visualization', '1', { packages: ['corechart'], "callback":drawVisualization}) but it didnt work. I am so lost at this point. what is the correct way to make google chart work under update panel/PageRequestManager? Thanks!
I don't think you need (or want) to use a document ready handler in your prm_EndRequest function. Try this instead:
function prm_EndRequest(sender, args) {
//Hide the loading image
var panelProg = $get('divImage');
panelProg.style.display = 'none';
//sort the table once retrieved from datatable from server
$("#table").dataTable({
"sScrollY": "400px",
"bPaginate": false
});
drawVisualization();
}
To make sure the Viz API code doesn't try to run before the API is finished loading, you should make sure to wrap whatever code you use to hook up the AJAX call to your button inside a callback from the google loader.

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