1

I'm new to JavaScript and am making an online map visualization. I need to read in a local csv file of geographical coordinates as an array.

For example, I have:

var data = [
  new google.maps.LatLng(40.3456455, -74.6558775),
  new google.maps.LatLng(40.3456456, -74.6558772),
  ];

And I want to be able to populate this with the coordinates I have in my CSV file.

I looked at jquery-csv but it requires the csv to be passed in as a string, and that passing a filepath and having Javascript read the file is not possible. Should I have the string hard-coded, or try and read it in in Python and somehow pass the string to Javascript? What is the best way to manage this?

Thanks!

AstroCB
  • 12,337
  • 20
  • 57
  • 73
user2009020
  • 287
  • 1
  • 3
  • 10
  • If you want the user to be able to supply the csv (rather than the server) then you need to look into the file API (and the drag and drop API if you want a nice UX) – david Dec 12 '14 at 21:39
  • No, I would want the server to supply it. How would I start implementing that? – user2009020 Dec 12 '14 at 21:47
  • In that case you should probably just grab it with ajax – david Dec 12 '14 at 22:09

2 Answers2

1

You can read the file and its contents with a Jquery get function example:

//the path to your csv file
var filePath ="pathToYourCSVFile";

$.get(filePath,function(data){


//do something with the data
//whatever you do with the data needs to been done inside this function


//example of what you could do

//array to hold the lines of your data file
//data string is split up by each new line
var lines = data.split("\n");

//you could then loop through each line and populate the values you need for each line



});
Larry Lane
  • 2,141
  • 1
  • 12
  • 18
0

If you want to read a local file, you need to use the HTML5 File API. After you have the CSV Data, I would parse it and convert to JSON. Here is a nice example including a link to a demo.

If you do not want to use the HTML5 File API, you can upload the CSV file to the server and convert the CSV to JSON there. Please find solution in PHP here.

I suggest you create a JSON like this, since this is easy to process with JavaScript on client side:

[
  {
    "latitude":40.3456455,
    "longitude":-74.6558775
  },
  {
    "latitude":40.3456456,
    "longitude":-74.6558772
  }
] 
Community
  • 1
  • 1
e-go
  • 21
  • 5
  • The HTML5 File API requires the user to upload the file, though. I don't want that-- I have the file and I want the program to automatically load it when the browser opens. – user2009020 Dec 12 '14 at 21:49
  • If it is OK to load the CSV from the server, then you can load it with JavaScript/jQuery and process it like in [the example](https://gist.github.com/iwek/7154578#file-csv-to-json-js) in my second link. – e-go Dec 12 '14 at 22:08
  • Actually both david and Larry Lane suggest something similar. Did you make some progress? – e-go Dec 13 '14 at 17:23