无法在Javascript中从csv读取数据

时间:2014-12-26 08:54:26

标签: javascript csv

我是Javascript的新手,在SO的帮助下,我编写了以下代码来读取csv文件。 计划: -

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
}
</style>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function csvToJS(csv) {
    // Split the text into an array of lines
    var rows = csv.split('\n');

    // Then we want each row to be an array too
    return rows.map(function(row) {
        // Split the row into an array too
        row = row.split(', ');

        // Values in quotes should be strings, values without are numbers
        return row.map(function(cell) {
           if (cell[0] == '\'') return cell.slice(1,-1);
           else return parseFloat(cell);
        });
    });
 }
var req = new XMLHttpRequest();
req.open('GET', 'data.csv', true);
req.send();

req.onreadystatechange = function() {
    if (req.readystate == 4 && req.status == 200) {
       var csv = req.responseText;
       var data = csvToJS(csv);


    }
};
    var citymap = data;
    var cityCircle;

    function initialize() {
        // Create the map.
        var mapOptions = {
            zoom : 5,
            center : new google.maps.LatLng(37.09024, -95.712891),
            mapTypeId : google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

        var fillcolor = [];
        fillcolor[0] = '#FF0000';
        fillcolor[1] = '#FFFF00';
        fillcolor[2] = '#FF00FF';
        fillcolor[3] = '#00FF00';
        fillcolor[4] = '#0000FF';
        var loop = 0;
        for (i = 0; i < citymap.length; i++) {
            var populationOptions = {
                strokeColor : '#000000',
                strokeOpacity : 0.8,
                strokeWeight : 2,
                fillColor : fillcolor[loop],
                fillOpacity : 0.35,
                map : map,
                center : new google.maps.LatLng(citymap[i][1], citymap[i][2]),
                radius : Math.sqrt(citymap[i][3]) * 100000
            };

            cityCircle = new google.maps.Circle(populationOptions);
            loop = loop + 1;

        }
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
    <div id="map-canvas"></div>
</body>
</html>

csv文件如下: data.csv

    'Chicago', 41.878113, -87.629798, 4
    'New York', 40.714352, -74.005973, 5 
    'Los Angeles', 34.052234, -118.243684, 3
    'Phoenix', 33.4483771, -112.0740373, 2 
    'Dallas', 32.7802618, -96.8009781, 5

但是我的代码没有显示地图。任何人都可以请看看它,并帮我修复我的代码。 我正在阅读csv (data.csv)并将其复制到数组data中。并将data复制到citymap。 我必须从csv

访问类似var city = citymap[0][0]的代码

1 个答案:

答案 0 :(得分:1)

不要盲目地将parseFloat用于所有字段,否则会使用'chicago'这样的名称,而其他字段则会提供 NaN

尝试使用:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Circles</title>
<style>
html, body, #map-canvas {
    height: 100%;
    margin: 0px;
    padding: 0px
}
</style>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function csvToJS(csv) {
    var resp=[];
    var rows = csv.split('\n');
     for(var i=0;i<rows.length;i++){
         var row=rows[i].split(',');
         row[0]=row[0].trim();
         row[1]=parseFloat(row[1]);
         row[2]=parseFloat(row[2]);
         row[3]=parseFloat(row[3]);
        resp[i]=row;
     }
     return resp;
 }
var citymap;
var req = new XMLHttpRequest();
req.open('GET', 'https://cdn.rawgit.com/agershun/alasql/version-0.0.36/examples/csv/demo.csv', true);
req.send();

req.onreadystatechange = function() {
     //console.log(req);
    if (req.status == 200) {
       var csv = req.responseText;
      var data = csvToJS(csv);
       citymap = data;
    }
    initialize();

};

    var cityCircle;

    function initialize() {
        // Create the map.
        var mapOptions = {
            zoom : 5,
            center : new google.maps.LatLng(37.09024, -95.712891),
            mapTypeId : google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'),
                mapOptions);

        var fillcolor = [];
        fillcolor[0] = '#FF0000';
        fillcolor[1] = '#FFFF00';
        fillcolor[2] = '#FF00FF';
        fillcolor[3] = '#00FF00';
        fillcolor[4] = '#0000FF';
        var loop = 0;
        for (i = 0; i < citymap.length; i++) {
            var populationOptions = {
                strokeColor : '#000000',
                strokeOpacity : 0.8,
                strokeWeight : 2,
                fillColor : fillcolor[loop],
                fillOpacity : 0.35,
                map : map,
                center : new google.maps.LatLng(citymap[i][1], citymap[i][2]),
                radius : Math.sqrt(citymap[i][3]) * 100000
            };

            cityCircle = new google.maps.Circle(populationOptions);
            loop = loop + 1;

        }
    }


</script>
</head>
<body>
    <div id="map-canvas"></div>
</body>
</html>