我正在尝试在Google地图变为空闲状态时触发功能。我之所以选择这样做,是因为javascript与某些html相关,并且如果我能更快地触发该函数,则该html尚未加载。
由于某些原因,仅当我移动地图或按F12时才会激活“空闲”侦听器。
函数initializeDoughnut
是从以下代码段中调用的:
source = new EventSource('http://localhost:4000/8housesdec')
source.addEventListener('message', function(e) {
if (e.lastEventId != -1) {
console.log("Processing new data");
processData(CSVToArray(e.data, ";"));
} else if (e.lastEventId == -1) {
smartHood = new Neighbourhood("Smart Hood");
setNeighbourhood(JSON.parse(e.data));
setWindowText();
}
}, false)
setNeighbourhood()
呼叫initializeDoughnut()
initializeDoughnut(map) {
console.log(this.name.replace(/\s/g, ''));
var doughnutMarker = createHTMLMapMarker({
latlng: new google.maps.LatLng((this.latlng.lat()+0.00006),(this.latlng.lng()-0.00007)),
map: map,
html: `<div id="canvas-holder`+this.name.replace(/\s/g, '')+`" class="doughnut">
<canvas id="chart-area`+this.name.replace(/\s/g, '')+`" width="110" height="110" />
</div>
`
})
google.maps.event.addListenerOnce(map, 'idle', function(){
this.loaddoughnut();
}.bind(this));
}
loaddoughnut() {
var colors = ['#27AE60','#E74C3C'];
var donutOptions = {
cutoutPercentage: 80,
legend: {display: false}
};
var donutData1 = {
labels: [],
datasets: [
{
backgroundColor: colors.slice(0,2),
borderWidth: 0,
data: [0, 0, 100],
label: "Doughnut 1"
},
]
};
var config = {
type: 'doughnut',
data: donutData1,
options: donutOptions
}
var ctx = document.getElementById("chart-area"+this.name.replace(/\s/g, '')).getContext("2d");
this.doughnutChart = new Chart(ctx, config);
}
当地图完全加载并且可以添加用于添加图形的html时,应调用loaddoughnut()函数。相反,只有在我移动地图或按某个按钮时才调用它。
我正在寻找一种更好的方法来在html可用时触发loaddoughnut函数。如果我不等待html加载,我会得到:
未捕获的TypeError:无法读取null的属性'getContext'