Highcharts.js输入数据的不同结构

时间:2016-12-12 16:19:32

标签: javascript jquery html highcharts

我有一个简单的Highcharts饼图,它将以下数据作为输入:

data: [
        {"y":4, "name":"Russia", "txt": "Our hotel at the countryside was very nice and welcoming."},
        {"y":2, "name":"Australia", "txt": "The trip to Ayers Rock was one of the highlights of our trip. The Great Barrier Reef and its clear water were simply amazing!"},
        {"y":1, "name":"Argentina", "txt": "It has been a childhood dream to just go into the wild."},
        {"y":4, "name":"China", "txt": "in year 1930 it was this is just a silly simple text to check if everything here is working."},
        {"y":2, "name":"Neverland", "txt": "in year 1940 it was like this."},
        {"y":4, "name":"Mars", "txt": "in year 1900 it was like this."}
            ]

示例:

$(document).ready(function() {
//var colors = ['#8d62a0', '#ceb3d8', '#d5dddd'];


    Highcharts.getOptions().plotOptions.pie.colors = (function () {
        var colors = [],
            base = '#801a00',
            i;

        for (i = 0; i < 100; i += 1) {
            colors.push(Highcharts.Color(base).brighten((i - 3) / 15).get());
        }
        return colors;
    }());

    var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'container',
            type: 'pie'
        },
        tooltip: {
              formatter: function() {
        				return '<b>'+this.point.name+'</b>';
        				}
         },
         legend: {
              enabled: false
         },

         plotOptions: {
            pie: {
                innerSize: '75%'
            },
            series: {
            	cursor: 'pointer',
            	point: {
            		events: {
            			 click: function(){
            				defineInnerData(this.y, this.txt, this);
        				},
       				}
        	     },
                 states: {
                  hover: {
                    enabled: false
                  }
                }
        	}
        },
        yAxis: {
            title: {
              text: null
            },
            labels: {
              enabled: false
            }
        },
        series: [{
            dataLabels: {
              enabled: false
            },

            data: [
        {"y":4, "name":"Russia", "txt": "Our hotel at the countryside was very nice and welcoming."},
        {"y":2, "name":"Australia", "txt": "The trip to Ayers Rock was one of the highlights of our trip. The Great Barrier Reef and its clear water were simply amazing!"},
        {"y":1, "name":"Argentina", "txt": "It has been a childhood dream to just go into the wild."},
        {"y":4, "name":"China", "txt": "in year 1930 it was this is just a silly simple text to check if everything here is working."},
        {"y":2, "name":"Neverland", "txt": "in year 1940 it was like this."},
        {"y":4, "name":"Mars", "txt": "in year 1900 it was like this."}
            ]
            }]
    });

    function defineInnerData(name, y, obj) { // on complete
        var chart=$("#container").highcharts();
        $( "#pieChartInfoText" ).remove();
        var textX = chart.plotLeft + (chart.plotWidth  * 0.5);
        var textY = chart.plotTop  + (chart.plotHeight * 0.5);
        var span = '<span id="pieChartInfoText" style="position:absolute; text-align:block;left: 235px;top:210px;width: 150px; height: 180px; overflow: scroll;">';
        span += '<span style="font-size: 11px">'+ y +'</span><br>';
        span += '</span>';

        $("#addText").append(span);
        span = $('#pieChartInfoText');
        span.css('left', textX + (span.width() * -0.5));
        span.css('top', textY + (span.height() * -0.5));
        span.css('overflow', 'auto');

    }
  
  defineInnerData("", "Click on the slices to see the text");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>

<div>
    <div id="container" style="position:absolute; left:0px; top:0px;"></div>
    <div id="addText" style="position:absolute; left:0px; top:0px;"></div>
</div>
<script src="testfile_highcharts.js"></script>

</body>
</html>

我现在的问题是:我如何读取数据作为输入,这些输入来自不同的结构,如下面的json代码(geoJSON),我希望将以下值作为输入我的图表:

  • 工具提示应显示国家/地区的名称(对应于geoJSON中的properties.name)。
  • 切片数对应data.features.articles的值(后者对应data.features.text中的句子数。)
  • 点击切片时,相应的句子(来自data.features.text)应显示在圆圈的中心。

以下是geoJSON数据的外观:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": 4,
      "properties": {
        "id": 4,
        "name": "Thailand",
        "lat": "13.7538929",
        "lon": "100.8160803",
        "2005": 14
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          "100.8160803",
          "13.7538929"
        ]
      },
      "text": ["The official reason given was that he wanted to give the Thai people time to mourn his father before he became king.", "Thailand has rarely had what might be called routine royal successions. The last was 70 years ago, when the young King Ananda was found shot dead in his bedroom in still unexplained circumstances."],
      "sentences": "2"
    },
    {
      "type": "Feature",
      "id": 7,
      "properties": {
        "id": 7,
        "name": "the United States",
        "lat": "38.8949549",
        "lon": "-77.0366455",
        "2005": 14
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          "-77.0366455",
          "38.8949549"
        ]
      },
      "text": ["The presidential elections will be a hard fight this year", "The best travelling season is September until end of October", "New York City is a must-see when travelling on the East Coast."],
      "sentences": "3"
    },
    {
      "type": "Feature",
      "id": 8,
      "properties": {
        "id": 8,
        "name": "Greece",
        "lat": "37.9841493",
        "lon": "23.7279843",
        "2005": 14
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          "23.7279843",
          "37.9841493"
        ]
      },
      "text": ["The Aegean islands are little paradise spots not far away from the bustling capital Athens "],
      "sentences": "1"
    }
  ]
}

我已经尝试了几个小时才能使这个工作,但我似乎无法做到这一点。我是JavaScript的新手,非常感谢这里的每一个帮助。如果对我的问题的解释不完全清楚,我也很抱歉,但我希望还有人可以帮助我...

2 个答案:

答案 0 :(得分:2)

实现这一目标的关键是将json结构化数据转换为所需结构中的javascript对象。

为此,您应该遍历json对象,获取所需的值并将其导出到您传递给图表的列表中。

&#13;
&#13;
// The empty list passed to chart
var dataToChart = [];

// Empty object of the list
var dataToChartObject = {"y":0, "name":"", "txt": ""}

// Iterate over jSon to populate dataToChartObject
$.each(jsonObject.features, function(index, value){
    
    dataToChartObject.name = value.properties.name;
    dataToChartObject.txt = value.text[0]
    
    // I didn't realize what the articles number is, but do the same logic to get it

    // Now let's insert the object to the list
    dataToChart.push(dataToChartObject);
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

这可以通过遍历JSON对象的属性来完成:

var featureSet = theJSON.features;
var theData = [];

for (var item in featureSet) {
        var set = featureSet[item];

        for (var theText in set.text) {
        var theSlice = {};
            theSlice.name = set.properties.name;
            theSlice.y = set.text.length;
            theSlice.txt = set.text[theText];

            theData.push(theSlice);
        }
}

其中theJSON是您返回的JSON对象。从这里,您可以修改图表以使用theData

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        type: 'pie'
    },
    tooltip: {
          formatter: function() {
                    return '<b>'+this.point.name+'</b>';
                    }
     },
     legend: {
          enabled: false
     },

     plotOptions: {
        pie: {
            innerSize: '75%'
        },
        series: {
            cursor: 'pointer',
            point: {
                events: {
                     click: function(){
                        defineInnerData(this.y, this.txt, this);
                    },
                }
             },
             states: {
              hover: {
                enabled: false
              }
            }
        }
    },
    yAxis: {
        title: {
          text: null
        },
        labels: {
          enabled: false
        }
    },
    series: [{
        dataLabels: {
          enabled: false
        },
        data: theData
        }]
});

示例jsFiddle。请注意,由于多个相同的名称/值切片,要选择切片的选择器不满意。我会为每个切片添加一个索引值,并改为关键。