我正在尝试使用d3.js
库向地图添加点数。
(我试图改编这个gist)的脚本。
问题是地图正在点上呈现。
我试图使用另一个SO答案,建议这样的事情:
svg.append("g").attr("id", "map").attr("id", "points")
...但我无法使其发挥作用。我是一个很长时间的python用户... JavaScript对我来说是新的(所以请原谅天真)。
使用以下CSS:
<style>
body {
background-color: white;
}
svg {
border: 1px solid black;
background-color: #a4bac7;
}
.land {
fill: #d7c7ad;
stroke: #8999ab;
}
.boundary {
fill: none;
stroke: #a5967f;
}
</style>
体:
<script type="text/javascript" src="d3/d3.js"></script>
<script src="http://d3js.org/topojson.v0.min.js"></script>
<script>
var width = 960;
var height = 480;
var dataURL = "https://gist.githubusercontent.com/abenrob/787723ca91772591b47e/raw/8a7f176072d508218e120773943b595c998991be/world-50m.json";
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
回答this回答答案,补充说:
svg.append("g")
.attr("id", "map")
.attr("id", "points");
var projection = d3.geoEquirectangular()
.scale(153)
.translate([width/2,height/2])
var path = d3.geoPath()
.projection(projection);
d3.json(dataURL, function(error, world) {
svg.append("g")
.select("#map").selectAll(".map")
.attr("class", "land")
.selectAll("path")
.data([topojson.object(world, world.objects.land)])
.enter().append("path")
.attr("d", path);
svg.append("g")
.select("#map").selectAll(".map")
.attr("class", "boundary")
.selectAll("boundary")
.data([topojson.object(world, world.objects.countries)])
.enter().append("path")
.attr("d", path);
}
);
var lngLatExtract = function(d, i){
return projection([d['lng'], d['lat']])[i];
};
d3.csv("cities.csv", function(data){
svg.append("g")
.select("#points").selectAll(".points")
.data(data)
.enter()
.append('circle')
.attr("cx", function(d){
return lngLatExtract(d, 0);
})
.attr('cy', function(d){
return lngLatExtract(d, 1);
})
.style("fill", "blue")
.style("opacity", 0.75)
.attr("r", function(d){
return Math.sqrt(parseInt(d['population']) * 0.000001)
});
}
);
</script>
cities.csv
看起来像这样:
rank,place,population,lat,lng
1,New York city,8175133,40.71455,-74.007124
2,Los Angeles city,3792621,34.05349,-118.245323
答案 0 :(得分:2)
d3.json
和d3.csv
都是 async 函数。它们的回调触发的顺序不是给定的,实际上因为你的csv文件较小,它的回调可能是先发射。这意味着您的csv回调中的svg.append("g")
发生在之前 json回调中的svg.append("g")
。您可以通过检查DOM并查看首先附加的内容来确认这一点。
那就是说,我会转而使用d3.queue。这允许您启动d3.json
和d3.csv
异步请求,然后触发单个回调,两者都完成。
另一个不太简化的选项是将d3.csv
代码放入d3.json
来电的回调中。