I am trying to query a csv file with google visualization query but every time I am getting 'Error in query: 404 file not found' error and am not able to resolve it.
any pointers / suggestions / thought would be highly appreciated.
Note - the csv file exists on my local server and if click on link http://localhost:35802/test.csv it downloaded the file for me
here is my code --
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
function initialize() {
//var opts = { sendMethod: 'auto' };
// Replace the data source URL on next line with your data source URL.
var query = new google.visualization.Query('csv?url=http://localhost:35802/test.csv');
// Optional request to return only column C and the sum of column B, grouped by C members.
query.setQuery('select * ');
// Send the query with a callback function.
query.send(handleQueryResponse);
}
function handleQueryResponse(response)
{
if (response.isError())
{
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
//alert(response);
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, { height: 400 });
}
</script>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(initialize);
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
here is my csv file content --
A,B,C
1,2,3
4,5,6
Thanks a lot #WhiteHat for the pointers.. finally I got it working...:)
the culprit was the google library that I was loading.
Initially I was loading --
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
which was not working for me...
I was able to run my code by changing this library to
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
for anyone who needs a working sample here it is --
please change the path to csv file
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
// var query = new google.visualization.Query('http://www.gstatic.com/external_hosted/gstatic/charts/static/data.csv',
// { csvColumns: ['string', 'number'], csvHasHeader: true });
var opt = { sendMethod: 'xhr' }; //{ csvColumns: ['string', 'number'], csvHasHeader: true, sendMethod: auto });
//var query = new google.visualization.Query('http://local:6572/data.csv', opt);
var query = new google.visualization.Query('http://localhost:6572/data.csv');
query.setQuery('select *');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' +
response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('csv'));
chart.draw(data, { legend: { position: 'none'} });
}
</script>
</head>
<body>
<div id="csv" style="width: 900px; height: 500px;"></div>
</body>
</html>
Related
Although I found similar posts elsewhere, I still cannot solve my issue.
I want to load locations on a html sidebar page on google spreadsheet, but the only example I find are hard-coded locations.
Here is an example, on HTML page (I removed API Key): this one works for me.
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "xxxx"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart(arrayToData) {
var data = new google.visualization.arrayToDataTable(
[["Lat", "Long","Nom"],
[45.7660889, 4.794056299999999, "Person1"],
[45.8167227, 4.8341048, "Person2"],
[45.7796433, 4.8037871, "Person3"],
[45.7780849, 4.921768399999999, "Person4"]]
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
</script>
</body>
And I would like to have something looking like that, where data locations are not hard-coded but comes from spreadsheet data :
google.charts.setOnLoadCallback(drawChart);
var ss = SpreadsheetApp.openByUrl("xxxx");
var datatable = ss.getRange("listNamesAdresses");
function drawChart(arrayToData) {
var dataToArray=document.getElementById("listNamesAdresses");
var data = new google.visualization.arrayToDataTable(
dataToArray
);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}//function drawChart() {
I'm aware this is not correct, but I tried many combinations, still cannot solve it. Your help is welcome !
Here is a sharable example of what I made :
Link to a copy of my Map Test
I adapted it from my spreadsheet but went out of my quota for my API key, so I could'nt test it yet. I hope this will be fine !
Many thanks in advance
EDIT 2 :
I followed ziganotschka's suggestions (thank you very much for your time) : I couldn't apply the HtmlCreateOutputFromFil("index.html") so I stuck to my code for displaying a sidepage Html. For the rest of it : I now have a map (first victory!).
But, it says : "no data points to show".
I checked on values return by getAddresses function, seems OK. For getting easier on it, I changed the function to an easier one : getGeoCodesAndNames. This one returns, as it says, geocode latitude, longitude, and name.
Here are my new code sample and link to the new version of the spreadsheet :
Gs-code :
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
Logger.log(a_values);
/* returns
[[Lat, Lon, Name],
[45.7660889, 4.79405629999999, person1],
[45.8167227, 4.8341048, person2],
[45.7796433, 4.8037871, person3],
[45.7780849, 4.921768399999999, person4]]
*/
return a_values;
}//function getGeoCodesAndNames(){
function testMap2(){
var template = HtmlService.createTemplateFromFile("carte2");
var html = template.evaluate();
html.setTitle("Display Map 2").setHeight(550).setWidth(550);
SpreadsheetApp.getUi().showModalDialog(html, "Locations")
}//function testCarte1(){
and HTML code :
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getGeoCodesAndNames();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyC4WPcWGMZRoqSAfZ0F4RzvWtN6Jy7hmdE"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}// function drawChart() {
}//function onSuccess (arrayToData){
</script>
And here is the link to the new spreadsheet version :
TestMap2
Do I need to publish it as a web app if I just want to have a side page ? On previous projects I had, I could add datas from a side-page to a spreadsheet without it. In the oppposite ways, can you confirm I need to do it ? I tried, did not change anything on my current result : maybe I made something wrong.
Many thanks again for your help !
EDIT 3 :
I finally got it : My geocode/address function were not returning a proper format for coordinates, because of two things :
1) I'm using French typing, ie dot are replaced with commas in numbers
2) I had to add one more """ symbol at beginning and ending of each string part in the array.
Here is the correct function (might be improved, but..does the job):
function getGeoCodesAndNames(){
//get addresses and names list
var namesAddresses=ss.getRange("ListNamesAddresses");
var a_values=namesAddresses.getValues();
for (var i=0;i<a_values.length;i++){
for (var j=0;j<a_values[0].length;j++){
var value=a_values[i][j];
if (typeof value == "string"){
a_values[i][j]="\"" + value + "\"";
}
}
}
return a_values;
}//function getGeoCodesAndNames(){
Many thanks to the people who helped me !
To combine using the Visualization API in Javascript with retrieving spreadsheet data with Apps Script - you need to use a WebApp
Use google.script.run to pass data from the serverside to clientside
Sample:
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index.html");
}
function getDatafromSheet(){
var ss = SpreadsheetApp.openByUrl("xxxx");
// getNamedRanges()[0] works if you have only one named range
var datatable = ss.getNamedRanges()[0].getRange().getValues();
return datatable;
}
index.html
<body>
<div class="container">
<div id="map_div" style="width: 500px; height: 500px"></div>
</div> <!-- CLOSE CONTAINER -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
window.onload = google.script.run.withSuccessHandler(onSuccess).getDatafromSheet();
function onSuccess (arrayToData){
google.charts.load("current", {
"packages":["map"],
"mapsApiKey": "AIzaSyDCKzjezYeUDd2ugtFnzokCIpV1YpLmmEc"
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable(arrayToData);
var map = new google.visualization.Map(document.getElementById('map_div'));
map.draw(data, {
showTooltip: true,
showInfoWindow: true
});
}
}
</script>
</body>
I'm trying to load my google spreadsheet into my very basic webapp but I keep getting this error "Cannot draw chart: no data specified." what I'm doing wrong ?
Here is my HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
const loaded = new Promise((res, rej) => {
google.charts.load('current');
google.charts.setOnLoadCallback(res);
});
let wrapper = null;
async function drawTable(arr) {
await loaded; //wait if charts is not loaded
wrapper = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: arr,
containerId: 'table_div',
});
wrapper.draw();
}
function getData(form) {
google.script.run
.withSuccessHandler(drawTable)
.getDataFromServer(form);//change server function name
}
</script>
</head>
<body>
<form>
<input type="text" name="searchtext" />
<input type="button" value="ok" onclick="getData(this.parentNode)" />
</form>
<div id="table_div"></div>
</body>
</html>
and here is my CODE.GS
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function getDataFromServer(e) {
var id ="1GRi3NAdannp3uNDi202HC5hKNMNIVMNw_WPDYIes5Hs";
var data = SpreadsheetApp.openById(id)
.getSheetByName("Daily report")
.getDataRange()
.getValues();
var ar = data.splice(0,1); //add headers
data.forEach(function(f) {
if (~f.indexOf(e.searchtext)) ar.push(f);
});
return ar;
}
And this is the link of my google spreadsheet .
https://docs.google.com/spreadsheets/d/1GRi3NAdannp3uNDi202HC5hKNMNIVMNw_WPDYIes5Hs/edit?usp=sharing
Thanks,
Here's a simple example of how I load data into a chart. First column date string and the other four columns are numbers.
function drawMealsChartOld(){
$('#btnC').css('background-color','#ffff00');
google.script.run
.withSuccessHandler(function(mObj){
var dt=mObj.dA;
var hA=dt[0];
dt.splice(0,1);
var dA=dt.slice();
var data = new google.visualization.DataTable();
for(var i=0;i<hA.length;i++){
if(i===0){
data.addColumn('string',hA[i]);
}else{
data.addColumn('number',hA[i]);
}
}
data.addRows(dA);
var options={
title:'Meals Grams (Starts: ' + mObj.start + ' - Ends: ' + mObj.end + ')',
fontSize: 14,
fontName: 'Roman',
width:640,
height:350,
pointSize:3,
hAxis:{slantedText:true,slantedTextAngle:90,textStyle:{color:'#333300',fontName:'Verdana',fontSize:8,bold:true}},
legend:{position:'top'},
chartArea:{left:75,top:75,width:'75%',height:'50%'},
series:{0: {targetAxisIndex: 0}, 1:{targetAxisIndex: 0}},
vAxes:[{title:'GRAMS',titleTextStyle:{color:'#0000CC',fontName:'Verdana',fontSize:12,bold:true,italic:false},textStyle:{color:'#0000CC',fontName:'Verdana',fontSize:10,bold:true,italic:false}}]
};
var chart=new google.visualization.LineChart(document.getElementById('mcht'));
//Not interested in emailing this chart I just want to be able to see how the average is doing.
//google.visualization.events.addListener(chart,'click',function(){emailVitalsDialog()});
//google.visualization.events.addListener(chart,'ready',function(){
//gImgObj['base64Data']=chart.getImageURI().split(',')[1];
//gImgObj.ready=true;
//});
chart.draw(data,options);
$('#btnC').css('background-color','#ffffff');
})
.getMealsData();
}
very quick question
i have webservice which returns JSON array
I want to display that JSON array in phonegap app
how can i do that
so far i was trying this
but its not working
$(document).ready(function () {
$.jsonp({
url: 'getevents.php',
callbackParameter: 'callback',
success: function (data, status) {
//$('#your-tweets').append('<li>The feed loads fine');
$.each(data, function (i, item) {
var tweet = item.title;
$('#your-tweets').append('<li>' + tweet);
});
},
error: function () {
$('#your-tweets').append('<li>There was an error loading the feed');
}
});
});
And here is my index.html file
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/data.js"></script>
<title>Hello World</title>
</head>
<body>
<ul id="your-tweets"></ul>
</body>
But with this code i am getting error that $.jsonp is not a function
If there are some tutorials available online than do provide me the link as well
I have tried this function as well
But somehow i cannot figure out where to pass the return array from the webservice
function readJSONData() {
$.getJSON("getevents.php",function(data){
if(data) {
var json_data;
$('#read-data').hide();
$('.demo-table').show();
$.each(data, function(i,event){
json_data = '<tr>'+
'<td valign="top">'+
'<div class="feed_title">'+event.title+'</div>'+
'<div>'+event.description+'</div>'+
'</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
});
} else {
json_data += '<tr>'+
'<td valign="top">No Tutorials Found</td>'+
'</tr>';
$(json_data).appendTo('#demo-table-content');
}
});
}
I can see in the firebug that on ajax request it returns the event array but on the page i get undefined instead of the data
thank you and really appreciate it
Use this prototype. And not event is an array so you have to check element in array i.e. data.event[index]
also you don't have any parameter data.event.desc so referring to that element will result undefined.
<html>
<body>
Get JSON Data
<div id="showdata"></div>
</body>
</html>
$(document).ready(function(){
//attach a jQuery live event to the button
$('#getdata-button').live('click', function(){
$.getJSON('http://dev.app.horsebuzz.com/dbconnection/getevents.php', function(data) {
//alert(data); //uncomment this for debug
//alert (data.item1+" "+data.item2+" "+data.item3); //further debug
for(var i=0;i<data.event.length;i++){
$('#showdata').html("<p>item1="+data.event[i].title+" item2="+data.event[i].start_date+" item3="+data.event[i].location+"</p>");
}
});
});
});
I have included the following files:
<script type="text/javascript" src="libs/png_support/zlib.js"></script>
<script type="text/javascript" src="libs/png_support/png.js"></script>
<script type="text/javascript" src="jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="jspdf.plugin.png_support.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="jspdf/jspdf.plugin.from_html.js"></script>
<script type="text/javascript" src="jspdf.js"></script>
And I am just testing if it could render a image through html:
var doc = new jsPDF();
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = '<img src="/assets/common/image/BG.jpg"/>';
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
It throws this error on console which says:
jsPDF Warning: rendering issues? provide a callback to fromHTML! (anonymous function)
I have used PNG format, since it was not working I also tried with JPG format, still no luck!
What am I doing wrong?
Thanks in advance.
Have one more argument for fromHTML()
doc.fromHTML(
source,
15,
15, {
'width': 180,
'elementHandlers': elementHandler
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
// pdf.save('Test.pdf');
if (navigator.msSaveBlob) {
var string = doc.output('datauristring');
} else {
var string = doc.output('bloburi');
}
$('.previewIFRAME').attr('src', string);
})
I´m trying to get an event in a google dashboard ChartWrapper.
I need that when I select a row i can throw an event and get the selected value.
Can anyone help me or say me how can I get it?
Here´s my code:
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['controls']});
</script>
<script type="text/javascript">
var data;
var table;
var dash_container;
var myDashboard;
var stringFilter;
var myTable;
function draw() {
// To see the data that this visualization uses, browse to
// http://spreadsheets.google.com/ccc?key=pCQbetd-CptGXxxQIG7VFIQ
data = new google.visualization.Query(
'http://spreadsheets.google.com/tq?key=0Ai3BbtO5JfaodGluSWw0UVFvZ3BDak1nYzVac0RPWGc&pub=1');
// Send the query with a callback function.
data.send(handleQueryResponse);
}
//fin de draw
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
table = response.getDataTable();
// Create a dashboard.
dash_container = document.getElementById('dashboard'),
myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control for the 'Name' column
stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'nombre'}
});
// Table visualization
myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0]} ,
'dataTable': table
});
// Register a listener to be notified once the dashboard is ready.
google.visualization.events.addListener(myDashboard, 'ready', dashboardReady);
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
}
**Here´s where I have the problems, because I can get the selection row
function dashboardReady() {
google.visualization.events.addListener(myTable, 'select', function(event) {
var selection = myTable.getChart().getSelection();
// iterate over all selected rows
for (var i = 0; i < selection.length; i++) {
// do something with selection[i].row
var item = selection[i];
}
alert('Fila seleccionada es: '+item.row +' y la Columna: '+item.column);
});
}
google.setOnLoadCallback(draw);
To do that, you need to do two things after the chart is drawn:
Add a 'ready' event listener to your chart wrapper;
Add a 'select' event listener to the table when the chart wrapper is ready.
So, add the following two lines after myDashboard.draw(table); in your code
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(){
var selection = myTable.getChart().getSelection();
alert(data.getValue(selection[0].row,0));
}
There will be about 3 seconds delay for the ready function to be triggered, due to a bug I think, see here for more details about the bug report of this issue: https://code.google.com/p/google-visualization-api-issues/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Stars%20Modified%20Type%20Status%20Priority%20Milestone%20Owner%20Summary&groupby=&sort=&id=1470
With Wrapper you have to add one more function to get selected item i.e. getChart()
Like:
var selectedItem = wrapper.getChart().getSelection()
Remember, Without Wrapper you was getting it by:
var selectedItem = chart.getSelection()
The code working ...
google.setOnLoadCallback(draw);
function draw() {
var data = [
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
];
var table = google.visualization.arrayToDataTable(data);
// Create a dashboard.
var dash_container = document.getElementById('dashboard');
var myDashboard = new google.visualization.Dashboard(dash_container);
// Define a StringFilter control.
var stringFilter = new google.visualization.ControlWrapper({
'controlType': 'StringFilter',
'containerId': 'filter',
'options': {'filterColumnLabel': 'Year'}
});
// Table visualization
var myTable = new google.visualization.ChartWrapper({
'chartType' : 'Table',
'containerId' : 'table',
'view': {'columns': [0, 1]} ,
'dataTable': table,
});
myDashboard.bind(stringFilter, myTable);
myDashboard.draw(table);
google.visualization.events.addListener(myTable , 'ready', function(){
google.visualization.events.addListener(myTable ,'select', tableSelectHandler);
});
function tableSelectHandler(e){
var selection = myTable.getChart().getSelection();
var t=table.getValue(selection[0].row, 0);
document.getElementById('label1').innerHTML = t;
}
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load('visualization', '1.1', {packages: ['controls']});</script>
<script type="text/javascript">
</script>
</head>
<body>
<div id="filter"></div>
<br>
<div id="table"></div>
<br>
<div id="label1"></div>
</body>
</html>