Creating Array from text file

I am working with Google Maps and Javascript, at the moment I am manually inputting marker information into an array like this;

function initMap()   
.....   
var markers = [
['Balham Leisure Centre',51.441234,-0.152297,'leisure_center.png'],  
['Putney Leisure Centre',51.463955,-0.228771,'leisure_center.png'],  
['Latchmere Leisure Centre',51.470967,-0.163805,'leisure_center.png'],  
]

however, would like to read the info from a file, so I have this function to do that;

function readFile(file)
{
    var f = new XMLHttpRequest();
    f.open("GET", file, false);
    f.onreadystatechange = function ()
    {
        if(f.readyState === 4)
        {
            if(f.status === 200 || f.status == 0)
            {
                var res= f.responseText;
                alert(res); //to see if contents are read
            }
        }
    }
    f.send(null);
}

readFile('test.txt');

This returns;

'Balham Leisure Centre',51.441234,-0.152297,'leisure_center.png'  
'Putney Leisure Centre',51.463955,-0.228771,'leisure_center.png'  
'Latchmere Leisure Centre',51.470967,-0.163805,'leisure_center.png'

How can I put this result into the array in the initMap function?

Hi @nazf355, if you replace the single quotes with double quotes your markers array would actually be a perfectly valid JSON file…

markers.json

[
  [
    "Balham Leisure Centre",
    51.441234,
    -0.152297,
    "leisure_center.png"
  ],
  [
    "Putney Leisure Centre",
    51.463955,
    -0.228771,
    "leisure_center.png"
  ],
  [
    "Latchmere Leisure Centre",
    51.470967,
    -0.163805,
    "leisure_center.png"
  ]
]

Then all you need to do is parse the response text:

var res = JSON.parse(f.responseText)

Otherwise you might look into a dedicated CSV parser library… doing that manually can be tricky with proper escaping and all. In its simplest form it might look like this though:

var res = f.split('\n').map(function (row) {
  return row.split(',')
})

This would split the response text at the line feeds, and each resulting row at the commas (regardless of if they are inside quotes ore not).

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.