调用JSON服务的Google图表工具的示例代码

时间:2013-01-10 20:43:32

标签: json charts

有人可以通过调用JSON API URL向我发送可以创建交互式图表的正确代码吗?

示例:基于URL中的JSON API的图表

http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo

在Google网站上,https://developers.google.com/chart/interactive/docs/php_example

中有一个示例

但是下面没有显示任何内容(我用我的URL替换了原始的JSON PHP文件位置)

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="jquery-1.6.2.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {
      var jsonData = $.ajax({
          url: "http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo ",
          dataType:"json",
          async: false
          }).responseText;

      // Create our data table out of JSON data loaded from server.
      var data = new google.visualization.DataTable(jsonData);

      // Instantiate and draw our chart, passing in some options.
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, {width: 400, height: 240});
    }

    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:2)

查看从您提供的网址返回的JSON(http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang = de&amp; username = demo),看起来它不符合DataTable JSON format

来自https://developers.google.com/chart/interactive/docs/basic_preparing_data

  

所有图表都需要数据。 Google Chart Tools图表需要数据   包含在名为google.visualization.DataTable的JavaScript类中。   此类在您可以在Google Visualization库中定义   以前加载过。 DataTable是一个包含行的二维表   和列,其中每列都有一个数据类型,一个可选的ID和一个   可选标签。

如果查看它们提供的示例JSON数据,您将看到它符合DataTable格式:

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}