简体   繁体   中英

Unable to read data from csv in Javascript

I am new to Javascript and with the help of SO I wrote the following code to read a csv file . Program:-

<!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>

The csv file is as follows : 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

But my code is not display the map. Can anyone please look into it and help me fix my code please .\\ I am reading the csv (data.csv) and copying it into an array data . And copying data to citymap . I have to access the code like var city = citymap[0][0] from csv

do not blindly use parseFloat for all fields otherwise for names like 'chicago' and other it will give NaN :

try using this:

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM