I am trying to create a custom state card using the Google charts API (showing the instant power off all my devices as a bar chart).
I am no expert in Polymer so I have a hard time linking everything properly.
The problem is I can’t have the charts updating in real time no matter what I try. The chart only updates on page refresh. Additionally, the Google charts events listeners seem not to work.
For sure I am doing something completely wrong with the code. I suspect something with the ready()
function, the positioning of the charts code or the way I am declaring the variable (in this case named state
). The variable updates as text but won’t reach the data object of the chart.
Any suggestions? More or less the question is how I update the ready
function on state change or any external script.
An alpha stage chart:
Below a simplified version of the code.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<dom-module id="state-card-chart">
<template>
<div id="myChart"></div>
</template>
</dom-module>
<script>
class Chart extends Polymer.Element {
static get is() { return 'state-card-chart'; }
static get properties() {
return {
hass: {
type: Object,
observer: 'hassChanged'
},
stateObj: {
type: Object,
},
config: {
type: Object,
computed: 'computeConfig(stateObj)',
},
};
}
computeConfig(stateObj) {
return stateObj.attributes.config;
}
_toStr(obj) {
return JSON.stringify(obj);
}
ready() {
super.ready();
var config = this.config;
var mychart = this.root.getElementById("myChart")
var state= parseInt(this.stateObj.state);
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['PC', state, '#b87333'],
['Laptop', 10, 'silver'],
['TV', 10, 'gold'],
['Fridge', 20, 'color: #e5e4e2' ]
]);
var options = {
title: "Instant power in W",
width: 450,
height: 400,
bar: {groupWidth: '50%'},
legend: { position: 'none' },
};
var chart = new google.visualization.ColumnChart(mychart);
chart.draw(data, options);
};
}
}
customElements.define(Chart.is, Chart);
</script>