Google Geo Charts:无法使用json数据绘制图表

时间:2015-09-07 08:58:27

标签: javascript json charts google-visualization

我在我的应用程序中使用谷歌地理图表。 我复制了数据库数据链接中给出的示例。

https://developers.google.com/chart/interactive/docs/gallery/geochart?hl=en

数据数组是

var data = google.visualization.arrayToDataTable([
        ['City',   'Population', 'Area'],
        ['Rome',      2761477,    1285.31]])

格式。

我以类似的模式向数据变量提供数据。但是看不到图表。

var arr=[];

         $.ajax({
            type: 'POST',
            url: "LiveMap",
            dataType: "json",
            success: function (response) {

               for (var i = 0; i < response.length; i++) {
                   var temp=[];
                  var str=response[i].split(':');
                  temp[0]=str[0];
                  temp[1]=parseInt(str[1]);
                  temp[2]=parseInt(str[2]);

                  arr[i]=temp;
               }
            }

         });

     google.load('visualization', '1', {'packages': ['geochart']});
     google.setOnLoadCallback(drawMarkersMap);

      function drawMarkersMap() {
          var data = new google.visualization.DataTable();
    data.addColumn("string","City");
    data.addColumn("number","Population");
    data.addColumn("number","Area");
    data.addRows(arr);
      var options = {
        region: 'IT',
        displayMode: 'markers',
        colorAxis: {colors: ['green', 'blue']}
      };

      var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    };
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 300px; height: 300px;"></div>
  </body>
</html>

对ajax调用的响应是

 result.put("Bhopal:300:200");
      result.put("Hyderabad:300:200");
      result.put("Vizag:300:200");
      result.put("Mysore:300:200");
      result.put("Delhi:300:200")

1 个答案:

答案 0 :(得分:0)

尝试在for循环后保留以下代码

google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap);

像这样:

$.ajax({
            type: 'POST',
            url: "LiveMap",
            dataType: "json",
            success: function (response) {

               for (var i = 0; i < response.length; i++) {
                   var temp=[];
                  var str=response[i].split(':');
                  temp[0]=str[0];
                  temp[1]=parseInt(str[1]);
                  temp[2]=parseInt(str[2]);

                  arr[i]=temp;
               }
               google.load('visualization', '1', {'packages': ['geochart']});
               google.setOnLoadCallback(drawMarkersMap);
            }

         });