0

有人可以通过调用 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

在谷歌网站上有一个示例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>
4

1 回答 1

2

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

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

所有图表都需要数据。Google Chart Tools 图表要求将数据包装在名为 google.visualization.DataTable 的 JavaScript 类中。此类在您之前加载的 Google 可视化库中定义。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}]}
      ]
}
于 2013-01-10T21:28:30.173 回答