Uncaught ReferenceError: google is not defined (Google Chart) - javascript

I'm new to require.js.
I'm trying to display Google Pie Chart.
I be able to get it working in my JSFiddle.
Issue
Then, when I move them into my real project, it doesn't work.
My real project using require.js
In my path, I declare it like this
'piechart' : 'reports/section-exercise/piechart',
In my piechart.js , I have it like this :
'use strict';
define(['jquery' ], function ($) {
$(function () {
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['l', 23],
['m', 30],
['h', 47],
]);
var options = {
width: 200,
height: 200,
chartArea: {
left: 10,
top: 20,
width: "100%",
height: "100%"
},
colors: ['#F46E4E', '#ADB55E', '#F9C262'],
legend: 'none',
enableInteractivity: false,
pieSliceText: 'none',
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
});
});
include
I included this link on top of my HTML file
<link rel="stylesheet" type="text/css" href="https://www.google.com/jsapi?autoload={%27modules%27:[{%27name%27:%27visualization%27,%27version%27:%271.1%27,%27packages%27:[%27corechart%27]}]}">
Result
Error Message
Then, when I clicked on the file on the right, it re-direct me to this line :
How do I stop that error and make my chart display again ?
How is my include link ? I used the same one in JSFiddle as external resources and it works.

You need to include that URL as JavaScript, but you're including it as CSS. You need this:
<script src="..."></script>
rather than this:
<link rel="stylesheet" type="text/css" href="...">

Related

How do you call a python api or local data into the js lib google.visualization.DataTable()?

I have been working for 2 weeks to try and get a CSV file (local) To load google.visualization.DataTable(). Or I would love to Us Ajax to call a Python flask API I created. I would like to create a Gantt chart dynamically.
My code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" ></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['gantt']});
google.charts.setOnLoadCallback(drawChart);
function daysToMilliseconds(days) {
return days * 24 * 60 * 60 * 1000;
}
function drawChart() {
var jsonData = $.ajax({
url: "http://127.0.0.1:5042/crudSEapi/D3test",
dataType: "json",
async: false
}).responseText;
var jsonData = JSON.parse(jsonData);
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Create our data table out of JSON data loaded from server.
console.log(jsonData["Column 0"])
data.addColumn('string',jsonData["Column 0"]);
data.addColumn(jsonData["Column 1"][1], jsonData["Column 1"][0]);
data.addRows([
[jsonData["Column 1"][2]]
]);
// Instantiate and draw our chart, passing in some options.
var options = {
height: 275,
gantt: {
criticalPathEnabled: false, // Critical path arrows will be the same as other arrows.
arrow: {
angle: 100,
width: 5,
color: 'green',
radius: 0
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Gantt(container);
// throw error for testing
google.visualization.events.addListener(chart, 'ready', function () {
throw new Error('Test Google Error');
});
// listen for error
google.visualization.events.addListener(chart, 'error', function (err) {
// check error
});
chart.draw(data, options);
}
</script>
<main id="main">
<section id="data-section">
<h2>Data Input</h2>
<div id="data"></div>
</section>
</main>
<h2>chart output</h2>
<div id="chart_div"></div>
<script>
function apicall(url) {
$.ajax({
type:"POST", url:url,
success: (data) => { $("#data").html(data); }
});
}
window.onload = function () {
apicall("http://127.0.0.1:5042/crudSEapi/D3test");
}
</script>
No mater how many YouTube videos I watch, I can't understand how to do an Ajax call from my Python Flask API AND load the needed data to google.visualization.DataTable() for dynamic creation of a Gantt chart:) please help
really my issue is a lack of Mastery of JS. How do I import data from API or a Local CSV? How do I Parse the data, then Organize the data to be used in google.visualization.DataTable(). I wish I could find a simple example. please help...
My Python Flask Api Code:
import json
#crudSEapi.route("/D3test", methods=["GET", "POST"])
def d3():
df = pd.read_csv("SkillBook/static/Sheet4.csv")
chartdata = df.to_json()
data = json.dumps(chartdata, indent=2)
print(data)
return Response(data)
CSV file:
id,title,start,end,dependencies,completed
m1,milestone 1,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),m2: start-to-start,0.6
m2,milestone 2,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),[m3: end-to-start,m4: end-to-end],0
m3,milestone 3,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.75
m4,milestone 4,addDuration(startOfDay(new Date()),addDuration(startOfDay(new Date()),,0.2
the output should look like this:
I figured it out thanks to #WhiteHat.
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://unpkg.com/jquery-csv#1.0.21/src/jquery.csv.js"></script>
<div id="chart_div"></div>
<li><input></li>
<li><input></li>
<li><input></li>
<button>update data in chart</button>
<button>print SVG</button>
<script>
function toMilliseconds(minutes) {
return minutes * 60 * 1000;
}
google.charts.load('current', {
callback: function () {
$.get("/static/Sheet4.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
console.log(arrayData[6][1])
var data = new google.visualization.DataTable();
data.addColumn(arrayData[2][1], arrayData[1][1]);
data.addColumn(arrayData[2][2], arrayData[1][2]);
data.addColumn(arrayData[2][4], arrayData[1][4]);
data.addColumn(arrayData[2][5], arrayData[1][5]);
data.addColumn(arrayData[2][6], arrayData[1][6]);
data.addColumn(arrayData[2][7], arrayData[1][7]);
data.addColumn(arrayData[2][8], arrayData[1][8]);
data.addRows([
[
arrayData[3][1],
arrayData[3][2],
null,
null,
toMilliseconds(5),
100,
null,
],
[
arrayData[4][1],
arrayData[4][2],
null,
null,
toMilliseconds(70),
100,
null,
],
[
arrayData[5][1],
arrayData[5][2],
null,
null,
toMilliseconds(10),
100,
arrayData[3][1],
],
[
arrayData[6][1],
arrayData[6][2],
null,
null,
toMilliseconds(45),
75,
arrayData[5][1],
],
[
arrayData[7][1],
arrayData[7][2],
null,
null,
toMilliseconds(10),
0,
arrayData[6][1],
],
[
arrayData[8][1],
arrayData[8][2],
null,
null,
toMilliseconds(2),
0,
arrayData[5][1],
],
]);
var options = {
height: 275,
gantt: {
criticalPathEnabled: false, // Critical path arrows will be the same as other arrows.
arrow: {
angle: 100,
width: 5,
color: 'green',
radius: 0
}
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Gantt(container);
chart.draw(data, options);
});
},
packages: ['gantt']
});
</script>
And my CSV:
step0,step1,step2,step3,step4,step5,Step6,step7,step8
Purpose,Task ID,Task Name,Resource ID,Start,End,Duration,Percent Complete,Dependencies
Data Type,string,string,string,date,date,number,number,string
Prject1data1,Test1,test1x,test1y,test1z,0,1,2,test1a
Prject1data2,Test2,test2x,test2y,test2z,0,1,2,test2a
Prject1data3,Test3,test3x,test3y,test3z,0,1,2,test3a
Prject1data4,Test4,test4x,test4y,test4z,0,1,2,test4a
Prject1data5,Test5,test5x,test5y,test5z,0,1,2,test4a
Prject1data6,Test6,test6x,test6y,test6z,0,1,2,test4a
Prject1data7,Test7,test7x,test7y,test7z,0,1,2,test4a
Next step:
Change Input To dynamic. I will create inputs form on website to change the data
I will allow CSV to be upload and parsed no mater the size of the CSV file

Google Chart Range Filter Control not working inside Android WebView

I made a simple HTML file and added it to my assets folder within my Android Studio. The file works perfectly when viewed directly on a browser. However, when viewed from inside of a webview or in a mobile device or emulator, the Google chart range controls are not draggable at all. The chart looks fine, but the controls are frozen. I can't find any help on this subject, so I would appreciate if someone could give me some pointers.
I have enabled Javascript on the webview and the jsapi.js is local inside of the assets folder too. Again, the chart looks fine. It's just the range control that is not working. Any ideas? The HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html; charset=UTF-8'>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type='text/javascript' src='jsapi.js'></script>
<!--TO TEST LOCALLY IN A BROWSER, USE THE LINE BELOW-->
<!--script type="text/javascript" src="https://www.google.com/jsapi"></script-->
<script type="text/javascript">
google.load('visualization', '1.0', {packages: ['controls']});
google.setOnLoadCallback(makeChart);
function makeChart( )
{
var maxWidth = 400;
var maxHeight = 400;
var data = new google.visualization.DataTable();
data.addColumn('number', 'Stock');
data.addColumn('number', 'Profit');
for(var x=10;x<50;x++){
data.addRow([x, x+1]);
}
var rangeFilter = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'range_filter_div',
options:{
filterColumnIndex: 0,
ui: {
chartOptions:{
width: maxWidth,
height: 50,
chartArea: { width: '75%' }
},
minRangeSize: 1
}
},
view: { columns: [0, 1] }
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: maxWidth,
height: maxHeight,
chartArea: { width: '75%' },
vAxis:{title:'Left Label'},
hAxis:{title:'Bottom Label'},
legend: 'none'
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind([rangeFilter], [chart]);
dash.draw(data);
}
</script>
</head>
<body>
<div id='dashboard'>
<div id='chart_div'></div>
<div id='range_filter_div'></div>
</div>
</body>
</html>
To enable Javascript on the WebView, here is the onCreate code for the main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.myWebView);
//JavaScript is disabled on webviews by default
WebSettings ws = wv.getSettings();
ws.setJavaScriptEnabled(true);
wv.loadUrl("file:///android_asset/index.html");
}
for starters, recommend using the newer library loader.js
<script src="https://www.gstatic.com/charts/loader.js"></script>
instead of jsapi, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this will only change the load statement, see following working snippet...
google.charts.load('current', {
callback: makeChart,
packages: ['controls']
});
function makeChart( )
{
var maxWidth = 400;
var maxHeight = 400;
var data = new google.visualization.DataTable();
data.addColumn('number', 'Stock');
data.addColumn('number', 'Profit');
for(var x=10;x<50;x++){
data.addRow([x, x+1]);
}
var rangeFilter = new google.visualization.ControlWrapper({
controlType: 'ChartRangeFilter',
containerId: 'range_filter_div',
options:{
filterColumnIndex: 0,
ui: {
chartOptions:{
width: maxWidth,
height: 50,
chartArea: { width: '75%' }
},
minRangeSize: 1
}
},
view: { columns: [0, 1] }
});
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'chart_div',
options: {
width: maxWidth,
height: maxHeight,
chartArea: { width: '75%' },
vAxis:{title:'Left Label'},
hAxis:{title:'Bottom Label'},
legend: 'none'
}
});
var dash = new google.visualization.Dashboard(document.getElementById('dashboard'));
dash.bind([rangeFilter], [chart]);
dash.draw(data);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<div id="range_filter_div"></div>
<div id="dashboard"></div>
Even ChartRangeFilter in example https://developers.google.com/chart/interactive/docs/gallery/controls#chartrangefilter_1 does not work on android browser. So code or library may not have anything to do with its non functionality, it simply may not be supported by android yet.

Getting an Uncaught TypeError: when i try to use my .tableExport in a button

I'm facing a huge problem since this morning, i'm trying to export my table into a pdf file. The script works fine if i put it in a without nothing else, the page load and the dl starts.
But i want it in a button ! And when i put it like this :
$(document).ready(function () {
$('#downloadPDF').on('click', function (e) {
console.log("test");
e.preventDefault();
$('table').tableExport({
type: 'pdf',
jspdf: {
orientation: 'l',
format: 'a3',
margins: {
left: 10,
right: 10,
top: 20,
bottom: 20
},
autotable: {
styles: {
fillColor: 'inherit',
textColor: 'inherit'
},
tableWidth: 'auto'
}
}
});
});
});
<button type="button" id="downloadPDF" class="btn btn-default">Default</button>
I get this error in the chrome console :
Uncaught TypeError: $(...).tableExport is not a function(anonymous function) # Auto:290jQuery.event.dispatch # jquery-1.10.2.js:5109elemData.handle # jquery-1.10.2.js:4780
I can't understand why. Because it works well when it's not in an event.
To do it, you need a table export plugin.
Add these imports in your page :
<script type="text/javascript" src="tableExport.js">
<script type="text/javascript" src="jquery.base64.js">
//and these if you want export to pdf
<script type="text/javascript" src="jspdf/libs/sprintf.js">
<script type="text/javascript" src="jspdf/jspdf.js">
<script type="text/javascript" src="jspdf/libs/base64.js">
Obviously, replace src paths by where you downloaded it.

Cannot read property 'BarRenderer' of undefined

i'm trying out jqplot just to use for bar graphs but no matter what example I try, i keep getting this error in the console:
"Cannot read property 'BarRenderer' of undefined"
i did a google search and can't find much of anything on this and i don't understand.. any help would be great. i'm using asp.net MVC 4
#{
ViewBag.Title = "View1";
}
<h2>View1</h2>
<script src="~/Scripts/jqPlot/jquery.min.js"></script>
<script src="~/Scripts/jqPlot/jquery.jqplot.min.js"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.barRenderer.min.js"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script src="~/Scripts/jqPlot/plugins/jqplot.pointLabels.min.js"></script>
<link href="~/Scripts/jqPlot/jquery.jqplot.css" rel="stylesheet" type="text/css">
<div id="chart1" style="height:400px;width:300px; "></div>
<script>
$(document).ready(function () {
var s1 = [200, 600, 700, 1000];
var s2 = [460, -210, 690, 820];
var s3 = [-260, -440, 320, 200];
// Can specify a custom tick Array.
// Ticks should match up one for each y value (category) in the series.
var ticks = ['May', 'June', 'July', 'August'];
var plot1 = $.jqplot('chart1', [s1, s2, s3], {
// The "seriesDefaults" option is an options object that will
// be applied to all series in the chart.
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { fillToZero: true }
},
// Custom labels for the series are specified with the "label"
// option on the series option. Here a series option object
// is specified for each series.
series: [
{ label: 'Hotel' },
{ label: 'Event Regristration' },
{ label: 'Airfare' }
],
// Show the legend and put it outside the grid, but inside the
// plot container, shrinking the grid to accomodate the legend.
// A value of "outside" would not shrink the grid and allow
// the legend to overflow the container.
legend: {
show: true,
placement: 'outsideGrid'
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
},
// Pad the y axis just a little so bars can get close to, but
// not touch, the grid boundaries. 1.2 is the default padding.
yaxis: {
pad: 1.05,
tickOptions: { formatString: '$%d' }
}
}
});
});
</script>
I've recreated the above snippet and it works fine. Are you sure all the files that you are including at the top of your script have been uploaded to your server? The only way I can replicate your error is by not uploading "jquery.jqplot.min.js" to my server.
Uncaught TypeError: Cannot set property 'BarRenderer' of
undefined(anonymous function) # jqplot.barRenderer.min.js:57(anonymous
function) # jqplot.barRenderer.min.js:57
I have faced same issue It is mainly related to js loading issue . Put those reference files in master layout page
Solved by removing the Scripts.Render at the bottom of View_Layout.cshtml
as it was calling jquery twice.
<div class="container body-content">
#RenderBody()
</div>
#Scripts.Render("~/bundles/jquery") <-- remove this line
#Scripts.Render("~/bundles/bootstrap") <-- remove this line
#RenderSection("scripts", required: false) <-- remove this line
</body>
</html>

Does google-visualization API refresh included fonts?

I have been doing an application which uses google-chart, google-fonts and awesome-fonts APIs. My main font is from google-fonts, I include them inside <head> tag, as well as the awesome-fonts.
However, when I use google-charts, fonts seems to be refreshed after the charts are loaded. By refresh, I mean, they seem like disappear and reload in a second. This makes my application seems weird. I didn't like it, and I'm not sure that google-charts is doing this effect.
here is my codesnippet to load google-charts;
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
function drawChart() {
var best_letters_data = google.visualization.arrayToDataTable(
JSON.parse('{{ best_letters|safe }}')
);
var worst_letters_data = google.visualization.arrayToDataTable(
JSON.parse('{{ worst_letters|safe }}')
);
var best_letters_options = {
title: 'Top Rated Hiragana Letters',
width: 450,
height: 240,
isHtml: true,
hAxis: {title: 'Letters', titleTextStyle: {color: 'red'}}
};
var worst_letters_options = {
title: 'Worst Rated Hiragana Letters',
width: 450,
height: 240,
isHtml: true,
hAxis: {title: 'Letters', titleTextStyle: {color: 'red'}}
};
var best_letters_chart = new google.visualization.ColumnChart(document.getElementById('best_letters_div'));
best_letters_chart.draw(best_letters_data, best_letters_options);
var worst_letters_chart = new google.visualization.ColumnChart(document.getElementById('worst_letters_div'));
worst_letters_chart.draw(worst_letters_data, worst_letters_options);
$("#loader").hide();
}
google.setOnLoadCallback(drawChart);
</script>
If I comment the lines which draws the charts ( best_letters_chart.draw(best_letters_data, best_letters_options); and worst_letters_chart.draw(worst_letters_data, worst_letters_options); ) my fonts are rendered one time, but well, the charts are not displayed with this time.
Why this is happening? I'm quite curious about this. If someone has any idea, please let me know.
Thanks in advance.

Categories

Resources