首页 > 解决方案 > D3 代码在 div 中创建 2 个 SVG 元素

问题描述

我制作了一张州地图,它采用 3 个不同的数据集(2 个 csv 和 1 个 json)并绘制出一张州地图,其中包含每个国家的人口数据,以及每个主要城市的圆圈。

我的问题是当我运行代码时,会创建 2 个单独的 svg 元素。

如果我在第一个 d3.csv() 函数之外定义 var svg=d3.select() ,则 DOM 上的第一个 svg 元素为空白,第二个 SVG 元素获得正确的映射。

如果我将 svg=d3.select() 放在第一个 d3.csv() 函数中,两个 SVG 元素都会获取地图。

我无法弄清楚第二个 SVG 的原因或来源,或者代码运行两次的原因

下面的代码在 d3.csv 中包含 var svg=d3... 地图上的所有内容都有效,我删除了很多过滤以使其更易于阅读,但如果您认为我需要,我可以添加代码至

var w = 960;
var h = 500;

//define the projection
var projection=d3.geoAlbers()
                .translate([w/2, h/2])
                .scale([1000]);

//Define path generator, using the Albers USA projection
var path = d3.geoPath()
                         .projection(projection);

//Create SVG element


//Load in GeoJson Data
var color=d3.scaleQuantize()
            .range(['rgb(66,146,198)','rgb(33,113,181)','rgb(8,81,156)','rgb(8,48,107)'])
//load the migration data, which will fill the states


d3.csv("http://127.0.0.1:8000/whyleave/migrations.csv").then(function(data){
  color.domain([
    d3.min(data, function(d) {return d.exemptions;}),
    d3.max(data, function(d) {return d.exemptions;})
  ]);
  data=data.filter(function(d){
    return d.State==stateab;})

d3.json("http://127.0.0.1:8000/whyleave/data.json").then(function(json){
  var ga=json.features.filter(function(feature){
    if (feature.properties.STATE == statenum)
    return feature.properties.STATE
  })
  var state = {
    "type": "FeatureCollection",
    "features": ga
  }
  projection.scale(1).translate([0,0])
  var b = path.bounds(state),
     s = .95 / Math.max((b[1][0] - b[0][0]) / w, (b[1][1] - b[0][1]) / h),
     t = [(w - s * (b[1][0] + b[0][0])) / 2, (h - s * (b[1][1] + b[0][1])) / 2];
  projection
   .scale(s)
   .translate(t);

 var svg = d3.select("#map")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);
  //Bind data and create one path per GeoJSON feature
  svg.selectAll("path")
      .data(state.features)
      .enter()
      .append('path')
      .attr("class", "nation")
      .attr("d", path)
      .style("stroke", "#fff")
      .style("stroke-width", "1")
      .style("fill", function(d){
        //get data value
        var value=d.properties.value;
        if (value){ return color(value);}
        else{return "rgb(198,219,239)";}
      });

        d3.csv("http://127.0.0.1:8000/whyleave/cities.csv").then(function(city){
          city=city.filter(function(d){
            return d.state_id==stateab & d.population > 250000;})
          svg.selectAll("circle")
              .data(city)
              .enter()
              .append("circle")
              .attr("cx", function(d){
                return projection([d.lng, d.lat])[0];
              })
              .attr("cy", function(d){
                return projection([d.lng, d.lat])[1];
              })
              .attr("r", "5")
              .style("fill", "yellow")
              .style("stroke", "gray")
              .style("stroke-width", 0.25)
              .style("opacity", 0.75);
              svg.selectAll("text")
                .data(city)
                .enter()
                .append("text")
                .attr('class', 'label')
                .attr("x", function(d){
                  return projection([d.lng, d.lat])[0];
                })
                .attr("y", function(d){
                  return projection([d.lng, d.lat])[1];})
                .text(function(d){
                  return d.city;
                })
                .attr("fill", "red");

              });

});});

标签: javascripthtmld3.jssvg

解决方案


我将脚本行放在正文之后的 html 上,当我将它们加载到正文中时,一切正常


推荐阅读