1

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

Newbie
  • 2,664
  • 7
  • 34
  • 75

1 Answers1

1

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>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
  • What if my csv has only `Chicago` and not `'Chicago'`? – Newbie Dec 26 '14 at 09:46
  • Yes its working but how do I scale if there are more cities in the csv ? – Newbie Dec 26 '14 at 09:53
  • But what if my csv has not single quotes? – Newbie Dec 26 '14 at 09:55
  • and another thing first take some time to properly get the flow of your code use console.log to see data and its format.this demo is to show you only, use your local file path in same way with same kind of data. – Suchit kumar Dec 26 '14 at 09:58
  • @Newbie you have posted another question just delete that or accept the proper answer to maintain the site image.`please` do not create unnecessary content here it will be good for all of us. – Suchit kumar Dec 26 '14 at 10:02
  • Hey I am unable to read a csv locally . I have the csv in the same directory as my code – Newbie Dec 26 '14 at 10:31
  • see what console says.do console.log(data) inside if condition and see what it has. – Suchit kumar Dec 26 '14 at 10:34
  • `XMLHttpRequest cannot load file:///data.csv. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.` – Newbie Dec 26 '14 at 10:41
  • it does, from where you read this.i also do not know about Cross origin requests but let me see what i can do. – Suchit kumar Dec 26 '14 at 10:46
  • Yes because we are sending get httprequest – Newbie Dec 26 '14 at 10:47
  • @Newbie read this post it will help.http://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading-a-local – Suchit kumar Dec 26 '14 at 10:51
  • Yes i stumbled on the same answer . Let me try – Newbie Dec 26 '14 at 10:53
  • Now this :( `http://localhost:8080/demo/data.csv` for `No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access` – Newbie Dec 26 '14 at 11:00
  • read this http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource or better post a new question based on current erors. – Suchit kumar Dec 26 '14 at 11:02
  • http://stackoverflow.com/questions/27656310/no-access-control-allow-origin-header-is-present-on-the-requested-resource-or – Newbie Dec 26 '14 at 11:20
  • Hey when I have "a","b","c","d" in csv the script is not working :( – Newbie Dec 26 '14 at 11:47
  • when you will do parseFloat for any of "a","b","c","d" it will give NaN so it will not able to make it LatLng object. – Suchit kumar Dec 26 '14 at 11:50