使用jQuery读取CSV以传递给Google可视化API

Using jQuery to read a CSV to pass to the Google Visualization API

本文关键字:Google 可视化 API jQuery 读取 CSV 使用      更新时间:2023-10-16

我正在尝试使用Google Visualization API的geochart包从CSV中的数据创建地图(https://google-developers.appspot.com/chart/interactive/docs/gallery/geochart)。工作流程如下:

  1. 使用jQuery将CSV转换为数组
  2. 将数组转换为数据表
  3. 从数据表生成图表

当我将数据直接编码为数组时,我能够生成映射;但是,我无法从CSV文件生成此数组。

我的代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
google.setOnLoadCallback(drawVisualizations);
function drawVisualizations() {
$.get("map_2003.csv", function(csv_in) {
var map_2003_in = $.csv.toArrays(csv_in, {onParseValue: $.csv.hooks.castToScalar});
var map_2003_data = new google.visualization.arrayToDataTable(map_2003_in);
var map_2003_chart = new google.visualization.GeoChart(document.getElementById('map_2003_chart'));
map_2003_chart.draw(map_2003_data, {'width': '640px','height': '480px'});
});
}
</script>
</head>
<body>
<div id="map_2003_chart" style="width: 640px; height: 480px;"></div>
</body>
</html>

我的CSV文件如下所示:国家,生产,美国,7362,加拿大,3003,墨西哥,3795,阿根廷,900,巴西,1548

任何帮助都将不胜感激。

假设您的CSV看起来像这样:

Country,Production
US,7362
Canada,3003
Mexico,3795
Argentina,900
Brazil,1548

我试过jQuery csv,它运行良好。因此,请确保CSV中的数据在多行上,而不是只有一行。