我想用谷歌图表制作一个插件,如下所示:
(function (global) {
'use strict';
if (!global.google || !global.google.charts) {
let s = document.createElement('script');
s.src = `//www.gstatic.com/charts/loader.js`;
document.head.appendChild(s);
}
let google = {};
google.ready = function (_) {
let t = setInterval(function () {
if (global.google && global.google.charts) {
clearInterval(t);
_.call(global.google);
}
}, 1);
};
let chart = (function () {
let _selector = Symbol('GoogleChart');
class GoogleChart {
constructor(selector) {
this[_selector] = selector;
}
CoreChart(options = {}) {
let _this = this, selector = document.getElementById(_this[_selector]);
let init = function () {
let google = this;
let drawChart = function () {
let O = {
width: options.width || 500,
height: options.height || 500,
legend: options.legend || {},
pointSize: options.pointSize || 1,
vAxis: options.vAxis || {},
hAxis: options.hAxis || {},
series: options.series || {},
colors: options.colors || [],
lineWidth: options.lineWidth || 2
};
let data = new google.visualization.DataTable();
if (!options.data || !options.data.columns || !options.data.rows) throw `Missing 'data'. No data to display in the chart.`;
for (let column in options.data.columns) data.addColumn(column, options.data.columns[column]);
if (options.tooltip && options.tooltip.type) {
let tooltip = {
type: options.tooltip.type,
role: 'tooltip'
};
if (options.tooltip.isHtml) {
tooltip.p = {
html: true
};
O.tooltip = {
isHtml: true
};
}
data.addColumn(tooltip);
}
data.addRows(options.data.rows);
//
let chart = new google.visualization.LineChart(selector);
//
chart.draw(data, O);
};
google.charts.load('current', { packages: ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
};
//
google.ready(init);
}
}
return GoogleChart;
}());
global.GoogleChart = chart;
}(window));
// USAGE:
let chart = new GoogleChart('line');
chart.CoreChart({
width: 500,
height: 200,
data: {
columns: {
'string': 'Date',
'number': 'Date'
},
rows: [
['1', 2],
['', 7],
['3', 3],
['', 9],
['5', 3],
['', 1],
['7', 4],
['', 6],
['9', 3],
['', 5],
['11', 8],
['', 2],
['13', 1],
['', 0],
['15', 8]
]
},
legend: {
position: 'top'
},
series: {
0: {
color: '#f00',
lineDashStyle: [2, 2, 20, 2, 20, 2]
}
},
pointSize: 3
});

<div id="line"></div>
&#13;
只有1种图表类型(CoreChart
)才能正常工作。现在,我想支持更多图表类型(Geo chart,Map chart)。
let chart1 = new GoogleChart(selector1);
chart1.GeoChart(options);
let chart2 = new GoogleChart(selector2);
chart2.MapChart(options);
我注意到the Limitations:
您只能在后拨打 google.charts.load 。但是您可以在一次通话中列出您需要的所有套餐,因此无需进行单独的通话。
因此,我的插件在调用(.GeoChart
或.MapChart
之前)并不确切知道图表类型。如果页面上有多个图表,如何绘制它?
如果我这样做:
google.charts.load('current', { packages: ['corechart', 'geochart', 'map'] });
并且没有调用GeoChart
或MapChart
,这会浪费(花时间加载未使用的图表)。
有什么想法吗?谢谢!