Javascript 将SVG项附加到现有元素之上
我正在尝试使用Javascript 将SVG项附加到现有元素之上,javascript,d3.js,svg,visualization,Javascript,D3.js,Svg,Visualization,我正在尝试使用d3.js库向地图添加点。 (我试着改编一个剧本) 问题是地图是在点的上面渲染的。 我尝试使用另一个SO答案,该答案建议如下: svg.append(“g”).attr(“id”、“map”).attr(“id”、“points”)…但我一直无法让它工作。我是python的长期用户…JavaScript对我来说是新的(所以请原谅我的天真) 我正在使用以下CSS: <style> body { background-color: white;
d3.js
库向地图添加点。
(我试着改编一个剧本)
问题是地图是在点的上面渲染的。
我尝试使用另一个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>
d3.json
和d3.csv
都是异步函数。它们的回调的触发顺序不是给定的,事实上,由于您的csv文件较小,它的回调可能首先触发。这意味着csv回调中的svg.append(“g”)
发生在json回调中的svg.append(“g”)
之前。您可以通过检查DOM来确认这一点,并查看哪个是先附加的
也就是说,我会转而使用。这允许您同时触发d3.json
和d3.csv
异步请求,然后在这两个请求都完成时触发单个回调
另一个简化程度较低的选项是将d3.csv
代码放在d3.json
调用的回调中
<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);
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>
rank,place,population,lat,lng
1,New York city,8175133,40.71455,-74.007124
2,Los Angeles city,3792621,34.05349,-118.245323