I am trying to debug this code and i tried to follow an example that works perfectly and i can get the chart and graphs to display without wrapper but once i make the change it falls apart ----[object Object] does not fit the Control specification.
WORKING code that puts all 3 on same view:
Project 1: Spreadsheet display working
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart', 'table']
});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(sendQuery);
// Construct and send a query to Google Spreadsheet
function sendQuery() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Ixlanep_0VfZtnk4rzS0jb1owTIbIRWAdGr9mp7OMIc/gviz/tq?tq=');
//query.setQuery('SELECT E, F, H, I');
query.send(drawChart);
}
// The query callback function
function drawChart(response) {
// Always check for error.
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
// Get DataTable from the "response" object. This is the result from your query.
// This DataTable must conform to the data format required by the chart you will draw next.
// To find out, read the Google Chart document at
// https://developers.google.com/chart/interactive/docs/
var data = response.getDataTable();
// Sort by the first column.
data.sort([{column: 0 }]);
//--------------------------------------------------------------------------
// Draw a table
//--------------------------------------------------------------------------
// We'll show the whole table. So there is no need to set call setColumns().
var tableView = new google.visualization.DataView(data);
// Create the table.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
var myTable = new google.visualization.Table(document.getElementById('table_div'));
myTable.draw(tableView);
//--------------------------------------------------------------------------
// Draw a chart #1
//--------------------------------------------------------------------------
// Create the chart #1.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins, loses, and NO# games behind .
var chartView = new google.visualization.DataView(data);
chartView.setColumns([4, 5]);
// Create the chart.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
var myChart = new google.visualization.ColumnChart(document.getElementById('chart1_div'));
myChart.draw(chartView);
//--------------------------------------------------------------------------
// Draw a chart #2
//--------------------------------------------------------------------------
// Create the chart #2.
// Note that DOM element ID must be consistent with the corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins, loses, and NO# games behind .
var chartView2 = new google.visualization.DataView(data);
chartView2.setColumns([0, 7, 8, 9]);
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
var myChart2 = new google.visualization.
ColumnChart(document.getElementById('chart2_div'));
myChart2.draw(chartView2);
}
</script>
</head>
<body>
<h2>Project 1: Spreadsheet display working</h2>
<!--Div that will hold the pie chart-->
<div id="table_div"></div>
<div id="chart1_div"></div>
<div id="chart2_div"></div>
</body>
</html>
PROBLEM CODE
<html>
<head>
<title>Project 1: Spreadsheet display working</title>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['controls', 'map',
'table', 'corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(sendQuery);
// Construct and send a query to Google Spreadsheet
function sendQuery() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1Ixlanep_0VfZtnk4rzS0jb1owTIbIRWAdGr9mp7
OMIc/gviz/tq?tq=');
//query.setQuery('SELECT E, F, H, I');
query.send(drawChart);
}
// The query callback function
function drawChart(response) {
// Always check for error.
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' +
response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// Sort by the first column.
data.sort([{column: 0 }]);
//------------------------------------------------------------------
// Draw a table
//------------------------------------------------------------------
// We'll show the whole table. So there is no need to set call
setColumns().
var tableView = new google.visualization.DataView(data);
// Create an empty ChartWrapper and set its properties
var chart1 = new google.visualization.ChartWrapper();
chart1.setChartType('Table');
chart1.setContainerId('table_div');
// To set a DataView for the ChartWrapper, use
DataView.toJSON()function.
// There is a no need to set DataTable for the ChartWrapper.
chart1.setView(tableView.toJSON());
//------------------------------------------------------------------
// Draw a chart #1
//------------------------------------------------------------------
// Create the chart #1.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins,
loses, and NO# games behind .
var chartView = new google.visualization.DataView(data);
chartView.setColumns([4, 5]);
var chart2 = new google.visualization.ChartWrapper();
chart2.setChartType('ColumnChart');
chart2.setContainerId('chart1_div');
chart2.setView(chartView.toJSON());
// Create the chart.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
//var myChart = new
google.visualization.ColumnChart(document.getElementById('chart1_div'));
//myChart.draw(chartView);
//------------------------------------------------------------------
// Draw a chart #2
//------------------------------------------------------------------
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
// We'll show home game attendance, runs scored, runs allowed, wins,
loses, and NO# games behind .
var chartView2 = new google.visualization.DataView(data);
chartView2.setColumns([0, 7, 8, 9]);
var chart3 = new google.visualization.ChartWrapper();
chart3.setChartType('ColumnChart');
chart3.setContainerId('chart2_div');
chart3.setView(chartView2.toJSON());
// Create the chart #2.
// Note that DOM element ID must be consistent with the
corresponding
// ID in the HTML body section.
//var myChart2 = new
google.visualization.ColumnChart(document.getElementById('chart2_div'));
//myChart2.draw(chartView2);
// Create and draw the dashboard
var dashboard = new
google.visualization.Dashboard(document.getElementById('dashboard_div'));
// Bind the filters to charts. These filters and charts now become
part of this dashboard.
dashboard.bind([chart1, chart2, chart3]);
// Draw all the charts and filters in this dashboard.
dashboard.draw(data);
}
</script>
</head>
<body>
<h2>Project 1: Spreadsheet display working</h2>
<div id="dashboard_div">
<table>
<tr>
<td>
<!--Div that will hold the pie chart-->
<div id="table_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
<br />
<div id="chart1_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
<br />
<div id="chart2_div" style="height: 200px; width: 1000px;
border-style: groove;">
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
Related
I am getting the data from MySQL and want to display it in a line chart using google charts. I am using java and javascript.
this is the type of data which i am getting from MySQL:
timestamp 2017-06-12 19:22:23.0 , 2017-06-12 19:22:25.0
f1 414 413
I got this data in a resultset and converted it into JSONarray and the output is like:
'[{"f1":414,"ts":"2017-06-12 19:22:23.0"},{"f1":415,"ts":"2017-06-12 19:22:25.0"}]'
-> from a servlet i am passing this string to a jsp file.
Now the JSP file:
<script type="text/javascript">
$(document).ready(function(){
alert('hello');
});
var newstring = <%= request.getAttribute("json_string")%>
<%System.out.println(request.getAttribute("json_string"));%>
var chartData = JSON.parse(newstring);
// Load google charts
google.load('visualization', '1.1', {packages:["corechart, table"]});
google.charts.setOnLoadCallback(drawChart);
// Draw the chart and set the chart values
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(data, options);
</script>
The chart is not getting displayed.
Any help would be appreciated. Or if there is any other way please write it down.
You are adding all your values to dTable while your are using some variable data while creating the chart, the correct way should be
chart.draw(dTable , options);
and there is no drawChart function , you should wrap everything in the function lioke
function drawChart(){
var dTable = new google.visualization.DataTable();
dTable.addColumn('string','timestamp');
dTable.addColumn('number','f1');
for(i=0;i<chartData.length;i++)
{
var currentObj = chartData[i];
dTable.addRow([currentObj.f1,currentObj.ts]);
}
// Display the chart inside the <div> element with id="linechart"
var options = {'title':'<%= request.getAttribute("Spring_type") + " for date :"%><%= request.getAttribute("date")%>', 'width':550, 'height':400};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(dTable , options);
}
Also look at this example from the api docs
In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};
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!
Im building a simple web page presenting a simple google pie chart according to data passed with JSstorage. the chart is located in another html file. Im trying to populate a div with the chart using AJAX.
the button that activates the drawing process:
<input type="button" name="showChart" value="Show Chart" onclick="drawChart()">
the div that will be populated with the chart:
<div id="placeForChart" style="width:800; height:700">
google chart goes here
</div>
the function that being called upon button click :
function drawChart()
{
$.jStorage.set("costsArr",costsArr);
document.getElementById('placeForChart'.innerHTML = loadChart('chart.html'));
function loadChart(href)
{
console.log("load chart function was called..");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseXML;
}
}
and finally the chart.html, which is pretty much the standard google's example, with modified content passed using JSstorage.
<head>
<script type="text/javascript">
var costsArr = $.jStorage.get('costsArr');
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['food', costsArr[0]],
['clothes', costsArr[2]],
['house holds', costsArr[1]],
['other', costsArr[3]]
]);
var options = {'title':'your expenses',
'width':500,
'height':400};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
This line will throw a syntax error:
document.getElementById('placeForChart'.innerHTML = loadChart('chart.html'));
Your closing parenthesis for the getElementById call is in the wrong place. It should be:
document.getElementById('placeForChart').innerHTML = loadChart('chart.html');
I suspect that you will need to strip any <html>, <head>, and <body> tags from chart.html. Also, you should probably load the visualization API on your main page and use a load event handler in chart.html to draw the chart.
I implemented the map on web page using JavaScript API, and now I want to show the basic information about some location. In JavaScript API documentation, I found a part of which is called "Basic place display" in Places Components section, but there is an example of how to render information using placeId.
I need to be able to retrieve information using location coordinates if it is possible. I tried to display information using PHP code that define coordinates for some location on the map instead of using placeId, but it's not working.
This is an example of code that I used:
var basicPlace = new nokia.places.widgets.Place({
placeId: PHP code instead of placeId.
*exp: [<?php code;?>, <?php echo code;?>],*
targetNode: "map",
template: "nokia.blue.place"
});
Is it possible to solve the problem like that, or there is a method that does not involve placeId.
Links: Here Developer, Here JavaScript API
If you read the nokia.places.widgets.Place documentation, you will see that placeId is a mandatory parameter. It is in effect the primary key for the place information that is held by HERE. You will therefore need to make another request using the JavaScript API prior to display in order to obtain the placeId so you can show your place details. The obvious thing to do here is to make a category request first, and store the placeId with each marker as shown below:
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
for (i = 0, len = locations.length; i < len; i++) {
// Add a marker and store the placeId
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
}
});
// etc.. etc...
The second part is to add the click listener which displays an infobubble and populates the Place Widget using the stored placeId:
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>",
evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
The complete working example can be seen below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=7; IE=EmulateIE9; IE=10" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Nokia Maps API for JavaScript Example: Search by category</title>
<meta name="description" content="Search by category"/>
<script type="text/javascript" charset="UTF-8" src="http://js.cit.api.here.com/se/2.5.3/jsl.js?with=all"></script>
</head>
<body>
<div id="mapContainer" style="width:540px; height:334px;"></div>
<script type="text/javascript" id="exampleJsSource">
/* Setup authentication app_id and app_code
*/
nokia.Settings.set("app_id", "YOUR APP ID");
nokia.Settings.set("app_code", "YOUR APP CODE");
// Use staging environment (remove the line for production environment)
nokia.Settings.set("serviceMode", "cit");
// Get the DOM node to which we will append the map
var mapContainer = document.getElementById("mapContainer");
// Create a map inside the map container DOM node
var map = new nokia.maps.map.Display(mapContainer, {
// Initial center and zoom level of the map
center: [52.51, 13.4],
zoomLevel: 10,
components: [
new nokia.maps.map.component.Behavior()
]
});
this.infoBubbles = new nokia.maps.map.component.InfoBubbles();
map.components.add(infoBubbles);
var searchCenter = new nokia.maps.geo.Coordinate(52.51, 13.4),
searchManager = nokia.places.search.manager,
resultSet;
// Function for receiving search results from places search and process them
var processResults = function (data, requestStatus, requestId) {
var i, len, locations, marker;
if (requestStatus == "OK") {
locations = data.results ? data.results.items : [data.location];
if (locations.length > 0) {
if (resultSet) map.objects.remove(resultSet);
resultSet = new nokia.maps.map.Container();
resultSet.addListener("click" , function(evt) {
infoBubbles.openBubble("<div id='basicPlaceContainer'></div>", evt.target.coordinate);
var basicPlace = new nokia.places.widgets.Place({
placeId: evt.target.placeId,
targetNode: "basicPlaceContainer",
template: "nokia.blue.bubble"
});
}, false);
for (i = 0, len = locations.length; i < len; i++) {
marker = new nokia.maps.map.StandardMarker(locations[i].position,
{ text: i+1 ,
placeId : locations[i].placeId});
resultSet.objects.add(marker);
}
map.objects.add(resultSet);
map.zoomTo(resultSet.getBoundingBox(), false);
} else {
alert("Your search produced no results!");
}
} else {
alert("The search request failed");
}
};
// Make a place search request
var category = "eat-drink";
map.addListener("displayready", function () {
searchManager.findPlacesByCategory({
category: category,
onComplete: processResults,
searchCenter: searchCenter
});
});
</script>
</body>
</html>
The result can be see below: