代码之家  ›  专栏  ›  技术社区  ›  OnLeRo

NVD3图表在传单控制中的应用

  •  0
  • OnLeRo  · 技术社区  · 7 年前

    我按照传单上的choropleth地图 tutorial 现在想在右上角的控件中包含一个NVD3图表。如果我要加收 <div> 除了地图,包括 <svg> 一切正常。我正在创建这样的信息控件:

    var info = L.control();
    
    info.onAdd = function(map) {
      this._div = L.DomUtil.create('div', 'info', ); // create a div with a class "info" 
      this.update();
      return this._div;
    };
    

    我用这样的内容来填充它:

    info.update = function(props) {
      this._div.innerHTML = (props ?
        '<h4>' + props.Name + '</h4>' + props.number :
        'Click on an area');
    };
    

    我试着在这里加入同样的内容 <div> 当我把它放在地图旁边时,它就起作用了 <div> :

    <div><svg/></div>
    

    但什么都没有出现。这是我的图表:

    function exampleData() {
      return [{
          "label": "One",
          "value": 29.765957771107
        },
        {
          "label": "Two",
          "value": 0
        },
        {
          "label": "Three",
          "value": 32.807804682612
        },
        {
          "label": "Four",
          "value": 196.45946739256
        },
        {
          "label": "Five",
          "value": 0.19434030906893
        },
        {
          "label": "Six",
          "value": 98.079782601442
        },
        {
          "label": "Seven",
          "value": 13.925743130903
        },
        {
          "label": "Eight",
          "value": 5.1387322875705
        }
      ];
    }
    
    nv.addGraph(function() {
      var chart = nv.models.pieChart()
        .x(function(d) {
          return d.label
        })
        .y(function(d) {
          return d.value
        })
        .showLabels(true);
    
      d3.select("#chart svg")
        .datum(exampleData())
        .transition().duration(350)
        .call(chart);
    
      return chart;
    });
    

    我认为这与 L.DomUtil.create 从这里开始 <div> 创建控制面板。但我没有告诉NVD3在控制面板中渲染绘图。你有什么想法吗?
    还有一件奇怪的事发生了:
    我在控制面板中看到文本下方的空白区域(应该在此处渲染图形)。如果我单击我的功能,文本会按预期进行更改,但下面的空白字段也会随着每次单击而增加。如果我包括 <div> 包含 <svg/> 在里面 info.update

    1 回复  |  直到 7 年前
        1
  •  1
  •   shabeer90    7 年前

    这个问题听起来并不复杂。一旦你读到我的解决方案,你可能会发笑。

    在创建pieChart时 nv.addGraph(function() {..} 在选择要渲染图表的元素的行中 d3.select("#chart svg") 浏览器假定DOM元素存在 ,但事实并非如此。

    你认为这与 L.DomUtil.create 。这就是你打电话的地方 this.update(); 要实际渲染 <div id="chart"> <svg/></div> NVD3 pieChart所需。

    这就是我对你的代码所做的。

    function createPieChart() {
      nv.addGraph(function() {
        var chart = nv.models.pieChart()
        ...  
        ...
        return chart;
      });
    }
    

    用一个 createPieChart() 功能,以便在 必需。

    在你的 info.update() 我打电话给 createPieChart() 创建innerHTML后,函数。

    // method that we will use to update the control based on feature properties passed
    info.update = function(props) {
      this._div.innerHTML = (...); //WHICH DIV HAS TO BE GENERATED
    
      // Now we can create the Pie Chart  
      createPieChart();
    };
    

    现在,它按预期工作。

    你可以找到一份工作 version here

    希望有帮助