Hello I am new to JavaScript but having difficulty with the generation of charts using the canvas.js library. The step that I am failing to replicate is the example on canvasjs website https://canvasjs.com/docs/charts/how-to/create-charts-from-csv/ for generating a chart using a csv document. Will I have to approach differently since I am hosting from google sheets?
My current code is:
<!DOCTYPE html>
<html>
<head>
<title>TEst</title>
<script type="text/javascript">
window.onload = function(){
var dataPoints = [];
function getDataPointsFromCSV(csv) {
var dataPoints = csvLines = points = [];
csvLines = csv.split(/[\r?\n|\r|\n]+/);
for (var i = 0; i < csvLines.length; i++)
if (csvLines[i].length > 0) {
points = csvLines[i].split(",");
dataPoints.push({
x: parseFloat(points[0]),
y: parseFloat(points[1])
});
}
return dataPoints;
}
//Replace text file's path according to your requirement.
$.get("https://docs.google.com/spreadsheets/d/12o9ekzln8KB3Uyg2fVou6UtIUlrC5GC973Ttk6GsjKs/edit?usp=sharing",function(data) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Chart from CSV",
},
data: [{
type: "line",
dataPoints: getDataPointsFromCSV(data)
}]
});
chart.render();
});
}
</script>
</head>
<body>
<p>it worked:</p>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
When I inspect with chrome I get the following error.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Hello there is already a good answer to this question, I added a link to the bottom of this answer.
It sounds like Google is not allowing you to load the data from their website.
Try replacing your dataPoints: getDataPointsFromCSV(data) with some example data from chart.js's site to make sure the rest of your code is working.
No 'Access-Control-Allow-Origin' header is present on the requested resource. with github sites
Related
I'm trying to figure out if BokehJS can meet my plotting needs for a minor dev project. When I try to copy the last example found on https://docs.bokeh.org/en/latest/docs/user_guide/bokehjs.html it fails with this backtrace in Chrome:
Uncaught TypeError: Cannot read property 'classList' of null
at c (bokeh-1.3.4.min.js:31)
at Object.n.add_document_standalone (bokeh-1.3.4.min.js:31)
at Object.t.show (bokeh-api-1.3.4.min.js:31)
at bokeh.html:58
The example is copied verbatim into a file, bokeh.html, and opened directly in the browser. bokeh.html:58 is the line
Bokeh.Plotting.show(plot);
The example is supposed to be a complete standalone html file so I must be missing something obvious here. My copy of the example can be found here https://pastebin.com/VizzJbH4
Any hints are greatly appreciated.
Move script tag with code at the end instead of head tag.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Complete Example</title>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-2.1.1.min.js" integrity="sha384-kLr4fYcqcSpbuI95brIH3vnnYCquzzSxHPU6XGQCIkQRGJwhg0StNbj1eegrHs12" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-2.1.1.min.js" integrity="sha384-xIGPmVtaOm+z0BqfSOMn4lOR6ciex448GIKG4eE61LsAvmGj48XcMQZtKcE/UXZe" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-2.1.1.min.js" integrity="sha384-Dc9u1wF/0zApGIWoBbH77iWEHtdmkuYWG839Uzmv8y8yBLXebjO9ZnERsde5Ln/P" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-gl-2.1.1.min.js" integrity="sha384-cT9JaBz7GiRXdENrJLZNSC6eMNF3nh3fa5fTF51Svp+ukxPdwcU5kGXGPBgDCa2j" crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-api-2.1.1.min.js" integrity="sha384-i2RsfqLVG6PTrWCD55m8pYN9N2XZRkYVASzqjzp79o0OpPmcp+APyuwCfItW7Kn2" crossorigin="anonymous"></script>
<script>
//The order of CSS and JS imports above is important.
</script>
</head>
<body>
</body>
<script>
// create a data source to hold data
var source = new Bokeh.ColumnDataSource({
data: { x: [], y: [] }
});
// make a plot with some tools
var plot = Bokeh.Plotting.figure({
title:'Example of Random data',
tools: "pan,wheel_zoom,box_zoom,reset,save",
height: 300,
width: 300
});
// add a line with data from the source
plot.line({ field: "x" }, { field: "y" }, {
source: source,
line_width: 2
});
// show the plot, appending it to the end of the current section
Bokeh.Plotting.show(plot);
function addPoint() {
// add data --- all fields must be the same length.
source.data.x.push(Math.random())
source.data.y.push(Math.random())
// notify the DataSource of "in-place" changes
source.change.emit()
}
var addDataButton = document.createElement("Button");
addDataButton.appendChild(document.createTextNode("Add Some Data!!!"));
document.currentScript.parentElement.appendChild(addDataButton);
addDataButton.addEventListener("click", addPoint);
addPoint();
addPoint();
</script>
</html>
I used arraytodatatable and tried to showed my data on the map, but I did not see any markers on the map.
Here is the code that I used
<html>
<head>
<title>Google Charts Tutorial</title>
<script type = "text/javascript" src =
"https://www.gstatic.com/charts/loader.js"></script>
<script type = "text/javascript" src =
"https://www.google.com/jsapi"></script>
<script type = "text/javascript">
google.charts.load('current', {packages: ['map'],'mapsApiKey': 'my
API'});
</script>
</head>
<body>
<div id = "container" style = "width: 550px; height: 400px; margin:
0
auto">
</div>
<script language = "JavaScript">
function drawChart() {
// Define the chart to be drawn.
var data = google.visualization.arrayToDataTable([
['Lat', 'Long', 'Name'],
[37.4232, -122.0853, 'Work'],
[37.4289, -122.1697, 'University'],
[37.6153, -122.3900, 'Airport'],
[37.4422, -122.1731, 'Shopping']
]);
// Set chart options
var options = {
showTip: true,
};
// Instantiate and draw the chart.
var chart = new
google.visualization.Map(document.getElementById('container'));
chart.draw(data, options);
}
google.charts.setOnLoadCallback(drawChart);
</script>
</body>
</html>
The error message I got was:
maps.google.com/mapfiles/ms/micons/red-dot.png:1 GET
file://maps.google.com/mapfiles/ms/micons/red-dot.png
net::ERR_FILE_NOT_FOUND
Does this mean the image that marker used does not exist anymore? If so, is there a way for me to change the color the marker so I can get the problem fixed?
I am new to web based visualization tool I used chartjs before but I did not find any solution for chartjs so, I transferred to canvasjs.Now I'm done creating the chart and it is successfully shown, thus I want to make it moving without refreshing because the data from the database is constantly moving. Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.getJSON("json.php", function(result){
var dps= [];
//Insert Array Assignment function here
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
}
//Insert Chart-making function here
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled:true,
panEnabled:true,
animationEnabled:true,
title:{
text: "myChart from mySQL database"
},
axisX:{
title: "TimeStamp"
},
axisY:{
title: "myDataPoints",
minimum: 0
},
data: [{
type: "spline",
dataPoints:
dps
}]
});
chart.render();
});
}
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
now, I would like to ask for help out there What do I need to keep this chart moving...??
If you want the lines to move, you need to remove dataPoints from the beginning of the array. You can do so using shift function in JS.
for(var i=0; i<result.length;i++) {
dps.push({"label":result[i].ts, "y":result[i].ph});
dps.shift();
}
This would do the trick for you.
So I have a working google chart that uses a CSV file, parses the CSV data as a string into an array, and uses the array as the datatable.
I actually asked a question and answered it myself Here.
That link will show you a full chunk of code that I used in my full working website.
I intended to just pull the script from the test file and drop it into my website, but now that I've moved it over and included the scripts I needed, I'm getting an error as:
Type Error: $.csv is undefined
Here is the code where $.csv is being utilized (var arrayData), this is a function for drawing the chart
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript"> // load the visualisation API
google.load('visualization', '1', { packages: ['corechart', 'controls'] });
</script>
<script type="text/javascript">
function drawVisualization() {
$.get("Thornton.M2.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
// CAPACITY - En-route ATFM delay - YY - CHART
var crt_ertdlyYY = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'crt_ertdlyYY',
dataTable: data,
options:{
width: 450, height: 160,
title: 'EU-wide en-route ATFM delays (year to date)',
titleTextStyle : {color: 'grey', fontSize: 11},
}
});
crt_ertdlyYY.draw();
});
}
google.setOnLoadCallback(drawVisualization)
</script>
</head>
<body>
<div id="crt_ertdlyYY"></div>
</body>
This example works fully as you can see from the link I had posted before hand, if you wanted to test it. But now that I pull it into my main site the .csv calls do not recognize. I also have 2 other google charts on this page that still work properly so it's isolated to this issue. I'm very new to google charts and pretty confused here!
Have been trying to follow the guide here to creating a pie chart and from there develop some dashboard features in Google Apps Script. I found out that when you implement the calling of a script function (in the example it would be the drawChart() function), that is considered "Active Content" as seen here.
I have seen other examples that don't use HTML, but those all seem to require the use of the UiApp class, which has been depreciated. So, is the only way to get a dashboard/graphing feature in Google Apps Script to have an HTTPS security certificate? It seems rather limiting if this is the case. I see a post or two mentioning a similar frustration getting only a white screen, and I believe that is due to the HTTPS limitation.
Originally I didn't post code because I felt the issue here was pretty clear. Here is the code I have. I also tried a simple HTML "Hello World" file that didn't have any functions/scripts, and that worked. Here is the script as it relates to my Google Sheet:
function OpenChart(){
var html = HtmlService.createHtmlOutputFromFile('DummyChart');
SpreadsheetApp.getUi().showModalDialog(html, "Statistics");
}
Here is the HTML file it calls:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
//Load charts package and visualization API
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(MakeChart);
//Here is the script I think could be causing a problem
function MakeChart()
{
var ss = SpreadsheetApp.getActive();
var s = ss.getSheets();
var s = sheets[1];
var UI = SpreadsheetApp.getUi();
var response = UI.prompt("Please enter the first cell in the category").getResponseText();
var ir = s.getRange(response);
var n= 0;
var stored = [];
stored.push(["Income Category", "Frequency"]);
while (ir.getValue()!= "") {
n = n +1;
ir = ir.offset(1, 0);
}
//Above we just set n, below we use n to fill our array
ir = ir.offset(-n,0)
for(i =0; i<n;i++) {
stored.push([ir.getValue(),ir.offset(n+2,0).getValue()]);
ir = ir.offset(1, 0);
}
var data = google.visualization.arrayToDataTable([
stored[]]);
/*I tried to also load data here directly as is seen on the pie chart example I used. This didn't have any affect*/
var options = { 'chartArea:backgroundColor': "Azure",
'is3D': true,
'title': 'Test Chart'};
//Now instantiate it
var chart = new google.visualization.PieChart(document.getElementById('chartDiv'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chartDiv" style="width: 450px; height: 300px;"> </div>
</body>
</html>
Any help appreciated.
Here is a quick example of how this can work. I stuck with the basic example and added the values from the pie chart example to the spreadsheet. The client side will need to call the server side to get the data. The is done with google.script.run. You would modify getData() to suite your needs.
code.gs:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("charts").addItem("piechart", "openPieChart").addToUi()
}
function openPieChart(){
var html = HtmlService.createHtmlOutputFromFile("piechart");
var ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, "piechart")
}
function getData(){
return SpreadsheetApp.getActiveSheet().getDataRange().getValues()
}
piechart.html
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(function(){google.script.run.withSuccessHandler(drawChart).getData()});
function drawChart(values) {
var data = google.visualization.arrayToDataTable(values);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>