我在为Google Gauge可视化动态创建代码时遇到了一些问题。我的主要问题是我正在尝试根据某些JSON中返回的内容构建javascript,以便为临时监控仪表板构建多个仪表板。这是我目前的代码:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
//Get php data about sensor into json array for javasript processing
var gauges = <?php echo json_encode($sensor_data);?>;
google.load("visualization", "1", {packages:["gauge"]});
google.setOnLoadCallback(drawChart);
for (var i = 0, len = gauges.length; i < len; ++i) {
var gauge = gauges[i];
var currentTemp = gauge.value;
var chartID = "chart_div_" + gauge.sensor_id;
var gMin = gauge.config_min_temp;
var gMax = gauge.config_max_temp;
var lLimit = gauge.limits_low;
var hLimit = gauge.limits_high;
//calculate major tick increments
var increment = (parseFloat(gMax) - parseFloat(gMin))/4;
var tick0 = gMin;
var tick1 = parseFloat(gMin) + parseFloat(increment);
var tick2 = parseFloat(tick1) + parseFloat(increment);
var tick3 = parseFloat(tick2) + parseFloat(increment);
var tick4 = gMax;
var Ticks = [tick0, tick1, tick2, tick3, tick4];
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temp', 0]
]);
var options = {
width: 220, height: 220,
redFrom: hLimit, redTo: gMax,
yellowFrom: gMin, yellowTo: lLimit,
greenFrom: gMin, greenTo: gMax,
minorTicks: 5,
majorTicks: Ticks,
min: gMin,
max: gMax,
redColor: '#ff0000',
yellowColor: '#ff0000',
greenColor: '#00cc00'
};
var chart = new google.visualization.Gauge(document.getElementById(chartID));
data.setValue(0, 1, currentTemp);
chart.draw(data, options);
}
}
</script>
我的问题是我无法创建数据对象的数组。我需要在for循环中引用该对象。我已经搜索了这个问题,直到我在我的智慧结束,并且无法想出一个很好的方法来做到这一点。我很乐意接受建议。提前谢谢。
答案 0 :(得分:0)
您的代码将按原样创建一个drawChart
函数,然后覆盖它,我相当肯定这不是您的意图。此代码将循环遍历gauges
数组,并为数组中的每个元素绘制一个Gauge:
function drawChart() {
for (var i = 0, len = gauges.length; i < len; ++i) {
var gauge = gauges[i];
var currentTemp = gauge.value;
var chartID = "chart_div_" + gauge.sensor_id;
var gMin = gauge.config_min_temp;
var gMax = gauge.config_max_temp;
var lLimit = gauge.limits_low;
var hLimit = gauge.limits_high;
//calculate major tick increments
var increment = (parseFloat(gMax) - parseFloat(gMin))/4;
var tick0 = gMin;
var tick1 = parseFloat(gMin) + parseFloat(increment);
var tick2 = parseFloat(tick1) + parseFloat(increment);
var tick3 = parseFloat(tick2) + parseFloat(increment);
var tick4 = gMax;
var Ticks = [tick0, tick1, tick2, tick3, tick4];
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temp', currentTemp]
]);
var options = {
width: 220, height: 220,
redFrom: hLimit, redTo: gMax,
yellowFrom: gMin, yellowTo: lLimit,
greenFrom: gMin, greenTo: gMax,
minorTicks: 5,
majorTicks: Ticks,
min: gMin,
max: gMax,
redColor: '#ff0000',
yellowColor: '#ff0000',
greenColor: '#00cc00'
};
var chart = new google.visualization.Gauge(document.getElementById(chartID));
data.setValue(0, 1, currentTemp);
chart.draw(data, options);
}
}
这是你想要完成的吗?