- Home
- Guides
- Reference
- Support
format[dataTable, srcColumnIndices,
opt_dstColumnIndex]
The standard formatting call, with a few additional parameters:
- dataTable - The DataTable on which to operate.
- srcColumnIndices - An array of one or more [zero-based] column indices to pull as the sources from the underlying DataTable. This will be used as a data source for the pattern parameter in the constructor. The column numbers do not have to be in sorted order.
- opt_dstColumnIndex - [optional] The destination column to place the output of the pattern manipulation. If not specified, the first element in srcColumIndices will be used as the destination.
See the formatting examples after the table.
Here are a few example inputs and outputs for a four-column table.
Row before formatting [4 columns, last is blank]: John | Paul | Jones | [empty] var formatter = new google.visualization.PatternFormat["{0} {1} {2}"]; formatter.format[data, [0,1,2], 3]; Output: John | Paul | Jones | John Paul Jones var formatter = new google.visualization.PatternFormat["{1}, {0}"]; formatter.format[data, [0,2], 3]; Output: John | Paul | Jones | Jones, John
Sample code
The following example demonstrates how to combine data from two columns to create an email address. It uses a DataView object to hide the original source columns:
var data = new google.visualization.DataTable[]; data.addColumn['string', 'Name']; data.addColumn['string', 'Email']; data.addRows[[ ['John Lennon', ''], ['Paul McCartney', ''], ['George Harrison', ''], ['Ringo Starr', ''] ]]; var table = new google.visualization.Table[document.getElementById['patternformat_div']]; var formatter = new google.visualization.PatternFormat[ '{0}']; // Apply formatter and set the formatted value of the first column. formatter.format[data, [0, 1]]; var view = new google.visualization.DataView[data]; view.setColumns[[0]]; // Create a view with the first column only. table.draw[view, {allowHtml: true, showRowNumber: true, width: '100%', height: '100%'}];
GadgetHelper
A helper class to simplify writing Gadgets that use the Google Visualization API.
Constructor
google.visualization.GadgetHelper[]
Methods
createQueryFromPrefs[prefs]
| google.visualization.Query | Static. Create a new instance of google.visualization.Query and set its properties according to values from the gadget preferences. The type of parameter prefs is _IG_Prefs
|
validateResponse[response]
| Boolean | Static. Parameter response is of type google.visualization.QueryResponse. Returns true if the response contains data. Returns false if the query execution failed and the response does not contain data. If an error occurred, this method displays an error message.
|
Query Classes
The following objects are available to send queries for data to an external data source, such as Google Spreadsheets.
- Query - Wraps the outgoing data request.
- QueryResponse - Handles the response from the data source.
Query
Represents a query that is sent to a data source.
Constructor
google.visualization.Query[dataSourceUrl, opt_options]
Parameters
dataSourceUrl [Required, String] URL to send the query to. See the Charts and Spreadsheets documentation for Google Spreadsheets. opt_options [Optional, Object] A map of options for the request. Note: If you are accessing a restricted data source , you should not use this parameter. Here are the supported properties:- sendMethod - [Optional, String] Specifies the method to use to send the query. Choose one of the following string values:
- 'xhr' - Send the query using XmlHttpRequest.
- 'scriptInjection' - Send the query using script injection.
- 'makeRequest' - [Available
only for gadgets, which are deprecated] Send the query using the Gadget API
makeRequest[]
method. If specified, you should also specify makeRequestParams. - 'auto' - Use the method specified by the
tqrt
URL parameter from the data source URL.tqrt
can have the following values: 'xhr', 'scriptInjection', or 'makeRequest'. Iftqrt
is missing or has an invalid value, the default is 'xhr' for same-domain requests and 'scriptInjection' for cross-domain requests.
- makeRequestParams - [Object] A map of parameters for a
makeRequest[]
query. Used and required only if sendMethod is 'makeRequest'.
Methods
abort[]
| None | Stops the automated query sending that was started with setRefreshInterval[] .
|
setRefreshInterval[seconds]
| None | Sets the query to automatically call the If you use this method, you should call it before calling the Cancel this method either by calling it again with zero [the default], or by calling |
setTimeout[seconds]
| None | Sets the number of seconds to wait for the data source to respond before raising a timeout error. seconds is a number greater than zero. The default timeout is 30 seconds. This method, if used, should be called before calling the send method.
|
setQuery[string]
| None | Sets the query string. The value of the string parameter should be a valid query. This method, if used, should be called before calling the send method. Learn more about the Query language.
|
send[callback]
| None | Sends the query to the data source. callback should be a function that will be called when the data source responds. The callback function will receive a single parameter of type google.visualization.QueryResponse.
|
QueryResponse
Represents a response of a query execution as received from the data source. An instance of this class is passed as an argument to the callback function that was set when Query.send was called.
Methods
getDataTable[]
| DataTable | Returns the data table as returned by the data source. Returns null if the query execution failed and no data was returned.
|
getDetailedMessage[]
| String | Returns a detailed error message for queries that failed. If the query execution was successful, this method returns an empty string. The message returned is a message that is intended for developers, and may contain technical information, for example 'Column {salary} does not exist'. |
getMessage[]
| String | Returns a short error message for queries that failed. If the query execution was successful, this method returns an empty string. The message returned is a short message that is intended for end users, for example 'Invalid Query' or 'Access Denied'. |
getReasons[]
| Array of strings | Returns an array of zero of more entries. Each entry is a short string with an error or warning code that was raised while executing the query. Possible codes:
|
hasWarning[]
| Boolean | Returns true if the query execution has any warning messages.
|
isError[]
| Boolean | Returns true if the query execution failed, and the response does not contain any data table. Returns if the query execution was successful and the response contains a data table.
|
Error Display
The API provides several functions to help you display custom error messages to your users. To use these functions, provide a container element on the page [typically a All functions are static functions in the namespace Many visualizations can throw an error event; see error event below to learn more about that. You can see an example custom error in the Query Wrapper
Example. Adds an error display block to the specified page element, with specified text and formatting. String ID value that identifies the error object created, or null if the response didn't indicate an error. This is a unique value on the page, and can be used to remove the error or find its containing element. Pass a query response and error message container to this method: if the query response indicates a query error, displays an error message in the specified page element. If the query response is null, the method will throw a JavaScript error. Pass your QueryResponse received in your query handler to this message to display an error. It will also set the style of the display
appropriate to the type [error or warning, similar to Removes the error specified by ID from the page. Removes all error blocks from a specified container. If the specified container does not exist, this will throw an error. Retrieves a handle to the container element holding the error specified by errorID. Most visualizations fire events to indicate something has occurred. As a user of the chart, you would often want to listen to these events. If you code your own visualization, you might also want to trigger such events on your own. The following methods enable developers to listen to events, remove
existing event handlers or trigger events from inside a visualization. Call this method to register to receive events fired by a visualization hosted on your page. You should document what event arguments, if any, will be passed to the handling function. Returns A listener handler for the new listener.
The handler can be used to later remove this listener if needed by calling google.visualization.events.removeListener[]. Example Here is an example of registering to receive the selection event This
is identical to An example of when this is useful: every draw causes a Call this
method to unregister an existing event listener. Call this method to unregister all event
listeners of a specific visualization instance. Called by visualization implementers. Call this method from your visualization to fire an event with an arbitrary name and set of values. Example Here is an example of a visualization that throws a method named "select" when its title method is called. It does not pass back any values. Every visualization should expose the following set of required and optional methods and properties. However, note that there is no type checking to enforce these standards, so you should read the documentation for each visualization. Note: These methods are in the namespace of the visualization, not the google.visualization namespace. The constructor should have the name of your visualization class, and return an instance of that class. Example Draws the visualization on the page. Behind the scenes this can be fetching a
graphic from a server or creating the graphic on the page using the linked visualization code. You should call this method every time the data or options change. The object should be drawn inside the DOM element passed into the constructor. Example
This is optionally exposed by visualizations that have tooltips and allow tooltip actions. Returns the tooltip action object with the
requested Example: This is optionally exposed by visualizations that want to let you access the currently selected data in the graphic. Returns selection_array An array of selected objects, each one describing a data element in the underlying table used to create the
visualization [a Example
This is optionally exposed by visualizations that have tooltips and allow tooltip actions. Removes the tooltip action
object with the requested Example: This is optionally exposed by visualizations that have tooltips and allow
tooltip actions. It works only for core charts [bar, column, line, area, scatter, combo, bubble, pie, donut, candlestick, histogram, stepped area]. Sets a tooltip action to be executed when the user clicks on the action text. The Any and all tooltip actions should be set prior to calling the chart's Example: The Example: Optionally selects a data entry in the visualization—for example, a point in an area chart, or a bar in a bar chart. When this method is called, the visualization should visually indicate what the new selection is. The implementation of Every time this method is called, all selected items are deselected, and the new selection list passed in should be applied. There is no explicit way to deselect individual items; to deselect individual items, call This section contains various useful methods exposed in the This method takes in a two-dimensional array and converts it to a DataTable. The column data types are determined automatically by the data provided.
Column data types can also be specified using the object literal notation in the first row [the column header row] of the array [i.e. Syntax Returns A new Examples The following code demonstrates three ways to create the same This method creates a chart in a single call. The advantage of using this method is that it requires slightly less code, and you can serialize and save visualizations as text strings for reuse. This method does not return a handle to the created chart, so you cannot assign method listeners to catch chart events. Syntax Examples Creates a table chart based on a spreadsheet data source, and includes the query SELECT A,D WHERE D > 100 ORDER BY D This next example creates the same table, but creates a This example passes in a JSON string representation of the chart, which you might have loaded from a file: This is the constructor for the toolbar element that can be attached to many visualizations. This toolbar enables the user to export the visualization data into different formats, or to provide an embeddable version of the visualization for use in different places. See the toolbar page for more information and a code example. Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For
details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Last updated 2021-03-22 UTC. [{ "type": "thumb-down", "id": "missingTheInformationINeed", "label":"Missing the information I need" },{ "type": "thumb-down", "id": "tooComplicatedTooManySteps", "label":"Too complicated
/ too many steps" },{ "type": "thumb-down", "id": "outOfDate", "label":"Out of date" },{ "type": "thumb-down", "id": "samplesCodeIssue", "label":"Samples / code issue" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]
google.visualization.errors
.FunctionReturn ValueDescription addError[container, message, opt_detailedMessage,
opt_options]
String ID value that identifies the error object created. This is a unique value on the page, and can be used to remove the error or find its containing element.
'background-color: #33ff99; padding: 2px;'
Default value is an empty string. addErrorFromQueryResponse[container, response]
addError[opt_options.type]
] removeError[id]
Boolean: true if the error was removed; false otherwise.
addError[]
or addErrorFromQueryResponse[]
. removeAll[container]
None
getContainer[errorId]
Handle to a DOM element holding the error specified, or null if it could not be found.
addError[]
or addErrorFromQueryResponse[]
. Events
addListener[]
google.visualization.events.addListener[source_visualization,
event_name, handling_function]
source_visualization
A handle to the source visualization instance.event_name The string name of the event to listen for. A visualization should document which events it throws. handling_function The name of the local JavaScript function to call when source_visualization fires the event_name event. The handling function will be passed any event arguments as parameters. var table = new google.visualization.Table[document.getElementById['table_div']];
table.draw[data, options];
google.visualization.events.addListener[table, 'select', selectHandler];
function selectHandler[] {
alert['A table row was selected'];
}
addOneTimeListener[]
addListener[]
, but is intended for events that should only be listened to once. Subsequent throws of the event will not invoke the handling function. ready
event to be thrown. If you want only the first ready
to execute your code, you'll want addOneTimeListener
rather than addListener
. removeListener[]
google.visualization.events.removeListener[listener_handler]
listener_handler The listener handler to remove, as returned by google.visualization.events.addListener[]. removeAllListeners[]
google.visualization.events.removeAllListeners[source_visualization]
source_visualization A handle to the source visualization instance from which all event listeners should be removed. trigger[]
google.visualization.events.trigger[source_visualization, event_name,
event_args]
source_visualization
A handle to the source visualization instance. If you are calling this function from within a method defined by the sending visualization, you can simply pass in the this
keyword. event_name A string name to call the event. You can choose any string value that you want. event_args [optional] A map of name/value pairs to pass to the receiving method. For example: {message: "Hello there!", score: 10, name: "Fred"}. You
can pass null if no events are needed; the receiver should be prepared to accept null for this parameter. MyVisualization.prototype. title = function[rowIndex] {
this.highlightRow[this.selectedRow, false]; // Clear previous selection
this.highlightRow[rowIndex, true]; // Highlight new selection
// Save the selected row index in case getSelection is called.
this.selectedRow = rowIndex;
// Trigger a select event.
google.visualization.events.trigger[this, 'select', null];
}
Standard Visualization
Methods and Properties
Constructor
visualization_class_name[dom_element]
dom_elementA pointer to a DOM element where the visualization should be embedded.var org = new google.visualization.OrgChart[document.getElementById['org_div']];
draw[]
draw[data[, options]]
data A DataTable
or DataView
holding the data to use to draw the chart. There is no standard method for extracting a
DataTable
from a chart. options [Optional] A map of name/value pairs of custom options. Examples include height and width, background colors, and captions. The visualization documentation should list which options are available, and should support default options if you do not specify this parameter. You can use the JavaScript object literal syntax to pass in an options map: e.g., {x:100, y:200, title:'An Example'}
chart.draw[myData, {width: 400, height: 240, is3D: true, title: 'My Daily Activities'}];
getAction[]
actionID
.// Returns the action object with the ID 'alertAction'.
chart.getAction['alertAction'];
getSelection[]
selection_array getSelection[]
DataView
or a DataTable
]. Each object has properties row
and/or column
, with the index of the row and/or column of the selected item in the underlying DataTable
. If the row
property is null, then the selection is a column; if the column
property is null, then the selection is a row; if both are non-null, then it is a specific data item. You can call the DataTable.getValue[]
method to get the value of the selected item. The retrieved array can be passed into setSelection[]
. function myClickHandler[]{
var selection = myVis.getSelection[];
var message = '';
for [var i = 0; i < selection.length; i++] {
var item = selection[i];
if [item.row != null && item.column != null] {
message += '{row:' + item.row + ',column:' + item.column + '}';
} else if [item.row != null] {
message += '{row:' + item.row + '}';
} else if [item.column != null] {
message += '{column:' + item.column + '}';
}
}
if [message == ''] {
message = 'nothing';
}
alert['You selected ' + message];
}
removeAction[]
actionID
from your chart. // Removes an action from chart with the ID of 'alertAction'.
chart.removeAction['alertAction'];
setAction[]
setAction[action object]
setAction
method takes an object as its action parameter. This object should specify 3 properties: id
— the ID of
the action being set, text
—the text that should appear in the tooltip for the action, and action
— the function that should be run when a user clicks on the action text. draw[]
method. // Sets a tooltip action which will pop an alert box on the screen when triggered.
chart.setAction[{
id: 'alertAction',
text: 'Trigger Alert',
action: function[] {
alert['You have triggered an alert'];
}
}];
setAction
method can also define two additional properties: visible
and enabled
. These properties should be functions that return boolean
values indicating if the tooltip
action will be visible and/or enabled. // The visible/enabled functions can contain any logic to determine their state
// as long as they return boolean values.
chart.setAction[{
id: 'alertAction',
text: 'Trigger Alert',
action: function[] {
alert['You have triggered an alert'];
},
visible: function[] {
return true;
},
enabled: function[] {
return true;
}
}];
setSelection[]
setSelection[]
should not fire a "select" event.
Visualizations may ignore part of the selection. For example, a table that can show only selected rows may ignore cell or column elements in its setSelection[]
implementation, or it can select the entire row. setSelection[]
with the items to remain selected; to deselect all
elements, call setSelection[]
, setSelection[null]
, or setSelection[[]]
. setSelection[selection_array]
selection_array An array of objects, each with a numeric row and/or column property. row
and column
are the zero-based row or column number of an item in the data table to select. To select a whole column, set row
to null; to select a whole row, set column
to null. Example: setSelection[[{row:0,column:1},{row:1, column:null}]]
selects the cell at [0,1] and the entire row 1. Assorted Static Methods
google.visualization
namespace. arrayToDataTable[]
{label: 'Start Date', type: 'date'}
]. Optional data roles may be used as well, but they must be defined explicitly using object literal notation. Object literal notation may also be used for any cell, allowing you to define
Cell Objects]. google.visualization.arrayToDataTable[twoDArray, opt_firstRowIsData]
twoDArray A two-dimensional array, where each row represents a row in the data table. If opt_firstRowIsData is false [the default], the first row will be interpreted as header labels. The data types of each column are interpreted automatically from the data given. If a cell has no value, specify a null
or empty value as appropriate. opt_firstRowIsData Whether the first row defines a header row or not. If true, all rows are assumed to be data. If false, the first row is assumed to be a header row, and the values are assigned as column labels. Default is false.DataTable
.DataTable
object:// Version 1: arrayToDataTable method
var data2 = google.visualization.arrayToDataTable[[
[{label: 'Country', type: 'string'},
{label: 'Population', type: 'number'},
{label: 'Area', type: 'number'},
{type: 'string', role: 'annotation'}],
['CN', 1324, 9640821, 'Annotated'],
['IN', 1133, 3287263, 'Annotated'],
['US', 304, 9629091, 'Annotated'],
['ID', 232, 1904569, 'Annotated'],
['BR', 187, 8514877, 'Annotated']
]];
// Version 2: DataTable.addRows
var data3 = new google.visualization.DataTable[];
data3.addColumn['string','Country'];
data3.addColumn['number','Population'];
data3.addColumn['number','Area'];
data3.addRows[[
['CN', 1324, 9640821],
['IN', 1133, 3287263],
['US', 304, 9629091],
['ID', 232, 1904569],
['BR', 187, 8514877]
]];
// Version 3: DataTable.setValue
var data = new google.visualization.DataTable[];
data.addColumn['string','Country'];
data.addColumn['number', 'Population'];
data.addColumn['number', 'Area'];
data.addRows[5];
data.setValue[0, 0, 'CN'];
data.setValue[0, 1, 1324];
data.setValue[0, 2, 9640821];
data.setValue[1, 0, 'IN'];
data.setValue[1, 1, 1133];
data.setValue[1, 2, 3287263];
data.setValue[2, 0, 'US'];
data.setValue[2, 1, 304];
data.setValue[2, 2, 9629091];
data.setValue[3, 0, 'ID'];
data.setValue[3, 1, 232];
data.setValue[3, 2, 1904569];
data.setValue[4, 0, 'BR'];
data.setValue[4, 1, 187];
data.setValue[4, 2, 8514877];
drawChart[]
google.visualization.drawChart[chart_JSON_or_object]
chart_JSON_or_object Either a JSON literal string or a JavaScript object, with the following properties [case-sensitive]:
PropertyTypeRequiredDefaultDescription chartType
String
Required
none
The class name of the visualization. The google.visualization
package name can be omitted for Google charts. If the appropriate visualization library has not already been loaded, this method will load the library for you if this is a Google visualization; you must load third party visualizations explicitly. Examples: Table
, PieChart
, example.com.CrazyChart
.
containerId
String
Required
none
The ID of the DOM element on your page that will host the visualization.
options
Object
Optional
none
An object describing the options for the visualization. You can use either JavaScript literal notation, or provide a handle to the object. Example: "options": {"width": 400, "height": 240,
"is3D": true, "title": "Company Performance"}
dataTable
Object
Optional
None
A DataTable
used to populate the visualization. This can be a literal JSON string representation of a DataTable, as described above, or a handle to a populated google.visualization.DataTable
object, or a 2-dimensional array like that accepted by
arrayToDataTable[opt_firstRowIsData=false]
. You must specify either this property or the dataSourceUrl
property.
dataSourceUrl
String
Optional
None
A data source query to populate the chart data [for example, a Google Spreadsheet]. You must specify either this property or the dataTable
property.
query
String
Optional
None
If specifying dataSourceUrl
, you can optionally specify a SQL-like query string using the Visualization query language to filter or manipulate the data.
refreshInterval
Number
Optional
None
How often, in seconds, the visualization should refresh its query source. Use this only when specifying dataSourceUrl
.
view
Object OR Array
Optional
None
Sets a DataView
initializer object, which acts as a filter over the underlying data, as defined by either the dataTable
or dataSourceUrl
parameter. You can pass in either a string or DataView
initializer object, like that returned by dataview.toJSON[]
. Example: "view": {"columns": [1, 2]}
You can also pass in an array of DataView
initializer objects, in which case the first DataView
in the array is applied to the underlying data to create a new data table, and the second DataView
is applied to the data
table resulting from application of the first DataView
, and so on.
google.charts.load['current']; // Note: No need to specify chart packages.
function drawVisualization[] {
google.visualization.drawChart[{
"containerId": "visualization_div",
"dataSourceUrl": "//spreadsheets.google.com/a/google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1",
"query":"SELECT A,D WHERE D > 100 ORDER BY D",
"refreshInterval": 5,
"chartType": "Table",
"options": {
"alternatingRowStyle": true,
"showRowNumber" : true
}
}];
}
google.charts.setOnLoadCallback[drawVisualization];
DataTable
locally:
google.charts.load['current'];
function drawVisualization[] {
var dataTable = [
["Country", "Population Density"],
["Indonesia", 117],
["China", 137],
["Nigeria", 142],
["Pakistan", 198],
["India", 336],
["Japan", 339],
["Bangladesh", 1045]
];
google.visualization.drawChart[{
"containerId": "visualization_div",
"dataTable": dataTable,
"refreshInterval": 5,
"chartType": "Table",
"options": {
"alternatingRowStyle": true,
"showRowNumber" : true,
}
}];
}
google.charts.setOnLoadCallback[drawVisualization];
google.charts.load['current'];
var myStoredString = '{"containerId": "visualization_div",' +
'"dataSourceUrl": "//spreadsheets.google.com/a/google.com/tq?key=pCQbetd-CptGXxxQIG7VFIQ&pub=1",' +
'"query":"SELECT A,D WHERE D > 100 ORDER BY D",' +
'"refreshInterval": 5,' +
'"chartType": "Table",' +
'"options": {' +
' "alternatingRowStyle": true,' +
' "showRowNumber" : true' +
'}' +
'}';
function drawVisualization[] {
google.visualization.drawChart[myStoredString];
}
google.charts.setOnLoadCallback[drawVisualization];
drawToolbar[]
Chủ Đề