一个基于Leaflet开发的小小小项目
问题大概只这样的:
首先是我用L.control()生成一个控件(info),通过.update()方法对控件进行更新。在.update()中我创建了一个新的canvas元素,之后通过document.getElementById()获取该元素,并使用Chart.js库创建一个饼图。在调用Chart.js库的时候就报错了(TypeError: item is null)。
相关资源:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js"></script>
<style>
#map{ height: 70% }
.info {
padding: 16px 10px;
font: 14px/16px Arial, Helvetica, sans-serif;
background: white;
background: rgba(255,255,255,0.8);
box-shadow: 0 0 15px rgba(0,0,0,0.2);
border-radius: 5px;
}
.info h4 {
margin: 0 0 5px;
color: 'white';
}
</style>
报错内容如下:
TypeError: item is nullChart.bundle.js:6904:14
acquireContext https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:6904
construct https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:8423
Chart https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js:8410
update http://127.0.0.1:5500/static/js/load_tiff.js:85
onAdd http://127.0.0.1:5500/static/js/load_tiff.js:76
addTo http://127.0.0.1:5500/static/js/leaflet/leaflet.js:5
<anonymous> http://127.0.0.1:5500/static/js/load_tiff.js:90
相关代码如下:
var randomScalingFactor = function() {
return Math.round(Math.random() * 100);
};
var config = {
type: 'pie',
data: {
datasets: [{
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
],
backgroundColor: [
"rgba(230, 14, 14, 1)",
"rgba(230, 122, 14, 1)",
"rgba(230, 230, 14, 1)",
"rgba(122, 230, 14, 1)",
"rgba(14, 122, 230, 1)",
],
label: 'Dataset 1'
}],
labels: [
'Red',
'Orange',
'Yellow',
'Green',
'Blue'
]
},
options: {
responsive: true
}
};
var info = L.control();
info.onAdd = function(mymap) {
this._div = L.DomUtil.create('div', 'info');
this.update();
return this._div;
};
info.update = function() {
var content = '<h4>Statistic Info</h4>' + '<br />';
content += '<canvas id="myChart" width="10" height="10"></canvas>';
this._div.innerHTML = content;
var piechart = new Chart(document.getElementById('myChart'),config)
};
info.addTo(mymap);