Код D3 создает 2 элемента SVG в DIV - PullRequest
0 голосов
/ 26 июня 2019

Я сделал карту штата, которая берет 3 разных набора данных (2 csv и 1 json) и выдает карту штата с данными о населении по стране и кружком в каждом крупном городе.

Моя проблема в том, что когда я запускаю код, создаются 2 отдельных элемента svg.

Если я определю var svg = d3.select () вне первой функции d3.csv (), первый элемент svgв DOM пусто, и второй элемент SVG получает правильную карту.

Если я помещу svg = d3.select () в первую функцию d3.csv (), оба элемента SVG получат карту.

Я не могу понять, почему или откуда приходит второй SVG, или почему код выполняется дважды

В приведенном ниже коде есть переменная svg = d3 ... внутри d3.csv... Все на карте работает, я удалил много фильтров, чтобы было легче читать, но я могу добавить код, если вы считаете, что мне нужно

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");

              });

});});

1 Ответ

0 голосов
/ 26 июня 2019

Я помещаю строки сценария в html после тела, когда я загружал их в тело, все работало нормально

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...