我将使用 here 中的基本示例,但我需要能够根据新数据(json 文件)更新 map 。我找不到直接在 Datamap 对象中加载数据的方法,所以我使用 D3.json 加载它并使用命令更新 map 。出于某种原因,popupTemplate 函数正在接收空数据对象,我不知道如何修复它。
做到这一点的最佳方法是什么?
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://datamaps.github.io/scripts/datamaps.world.min.js"></script>
<script src="http://datamaps.github.io/scripts/topojson.js"></script>
<div id="container" style="position: relative; width: 500px; height: 300px;"></div>
<script>
var data;
var map = new Datamap({
element: document.getElementById('container'),
fills: {
HIGH: '#afafaf',
LOW: '#123456',
MEDIUM: 'blue',
UNKNOWN: '#FFFFFF',
defaultFill: 'green'
},
geographyConfig: {
popupTemplate: function(geo, data) {
console.log(data)
return ['<div class="hoverinfo"><strong>',
'Number of things in ' + geo.properties.name,
': ' + data[geo.id].numberOfThings,
'</strong></div>'].join('');
}
}
});
map.legend();
d3.json("path/to/data.json", function(error, json) {
if (error) return console.warn(error);
data = json;
map.updateChoropleth(data);
});
</script>
这是我的 json 文件:
{
"IRL": {
"fillKey": "LOW",
"numberOfThings": "2002"
},
"USA": {
"fillKey": "MEDIUM",
"numberOfThings": "10381"
}
}
为了方便调试,我加了jsfiddle
最佳答案
我在 Datamap 中直接加载数据没有问题。在任何情况下,我还模拟了数据更新……颜色会更新,但值不会更新(numberOfThings)。在本教程的示例中,不清楚可以这样做,尽管应该能够更新值是有意义的。
我要离开你FIDDLE显示我的实验结果。
一些注意事项:
成为
data.numberOfThings
. 关于json - 使用新数据启动 D3.js 数据映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076077/